如何打印我创建的文件的名称?
How can I print name of the file that I created?
def creation():
#create file and ask name of file
#1st input - file name is loki.txt
#2nd input what do we want to write inside txt file
f = open(input("Minkäniminen tiedosto luodaan?: "), "w")
f.write(input('Mitä kirjoitetaan tiedostoon?:'))
f.close()
creation()
def main():
#file read and printing
tiedosto = open("loki.txt","r")
text = tiedosto.read()
print(text)
f.close()
return
#last print the name of file and txt inside of txt
print("Luotiin tiedosto", f.name, 'ja siihen tallennettiin teksti:', text)
我的问题是如何将该文件名打印到最后一行。
错误描述为:NameError name 'f' is not defined
一个选项是将名称保存在一个变量中并 return 它在 creation
:
def creation():
fname = input("Minkäniminen tiedosto luodaan?: ")
f = open(fname, "w")
f.write(input('Mitä kirjoitetaan tiedostoon?:'))
f.close()
return fname
fname = creation()
print("Luotiin tiedosto", fname, 'ja siihen tallennettiin teksti:', text)
def creation():
fileName = input("Minkäniminen tiedosto luodaan?: ")
if fileName:
with open(fileName, "w") as f:
txt = input('Mitä kirjoitetaan tiedostoon?:')
f.write(txt)
return fname
createdFile = creation()
print(f"Luotiin tiedosto {createdFile`enter code here`} ja siihen tallennettiin teksti: {txt}")
def creation():
#create file and ask name of file
#1st input - file name is loki.txt
#2nd input what do we want to write inside txt file
f = open(input("Minkäniminen tiedosto luodaan?: "), "w")
f.write(input('Mitä kirjoitetaan tiedostoon?:'))
f.close()
creation()
def main():
#file read and printing
tiedosto = open("loki.txt","r")
text = tiedosto.read()
print(text)
f.close()
return
#last print the name of file and txt inside of txt
print("Luotiin tiedosto", f.name, 'ja siihen tallennettiin teksti:', text)
我的问题是如何将该文件名打印到最后一行。
错误描述为:NameError name 'f' is not defined
一个选项是将名称保存在一个变量中并 return 它在 creation
:
def creation():
fname = input("Minkäniminen tiedosto luodaan?: ")
f = open(fname, "w")
f.write(input('Mitä kirjoitetaan tiedostoon?:'))
f.close()
return fname
fname = creation()
print("Luotiin tiedosto", fname, 'ja siihen tallennettiin teksti:', text)
def creation():
fileName = input("Minkäniminen tiedosto luodaan?: ")
if fileName:
with open(fileName, "w") as f:
txt = input('Mitä kirjoitetaan tiedostoon?:')
f.write(txt)
return fname
createdFile = creation()
print(f"Luotiin tiedosto {createdFile`enter code here`} ja siihen tallennettiin teksti: {txt}")