Python:用户输入文件名以写入/写入. 程序然后打开/读取



我对编程很陌生,我的任务是编写一个无用的程序来帮助学习如何编写一些不是从书本中出来的函数代码。该程序的目的是使用用户输入的文件名编写文件,然后将内容添加到文件中。我已经走到了这一步。我遇到的问题来自程序的后半部分。

后半部分假设向您读取它刚刚制作的文件的内容。 然后询问您是否要将内容复制到新文件。 然后为新文件分配用户输入的名称并复制原始文件的内容。

我在读取旧文件名时遇到问题。 而且我的程序输出如下所示:

Insert 'filename.txt' Here >>> test.txt
user input >>> lolokay
Traceback (most recent call last):
File "testbed.py", line 45, in <module>
main()
File "testbed.py", line 43, in main
copyToNew(newFile())
File "testbed.py", line 23, in copyToNew
oldFile = open(f"{f}", "r")
OSError: [Errno 22] Invalid argument: "<_io.TextIOWrapper name='test.txt' mode='w+' encoding='cp1252'>"

完整代码如下:

# this program will open a file or make a new file and write to it.
# it will then copy the file contents to a new file.
def newFile():
# opens user inputted filename ".txt" and (w+) makes new and writes
f = open(input("Insert 'filename.txt' Here >>> "), 'w+')
# asks for user input to enter into the file
usrInput = input("user input >>> ")
# writes user input to the file and adds new line
f.write(usrInput)
f.write("n")
# closes the file
return f
f.close()
# copy contents and outputs to new file
def copyToNew(f):
oldFile = open(f"{f}", "r")
fileContents = oldFile.read()
print("n",fileContents)
# needs to asks user if they would like to copy file to new document
print(f"Would you like to copy this (name{oldFile})? Y or N")
usrInput = input("Y or N >>> ")
print(usrInput)
if usrInput.lower() in {"y"}:
print("Your file has been created.")
elif usrInput.lower() in {"n"}:
print("Goodbye.")
else:
copyToNew(f)
# defines main
def main():
copyToNew(newFile())
main()

问题就在这里:

oldFile = open(f"{f}", "r")

open函数需要一个文件名,一个像"test.txt"这样的字符串。

f是一个文件对象。因此,f"{f}"是该文件对象的字符串表示形式,例如"<_io.TextIOWrapper name='test.txt' mode='w+' encoding='cp1252'>".您很幸运,您在Windows上,这不是有效的文件名;在macOS或Linux上,您实际上会创建一个具有该可怕名称的文件,直到后来才意识到问题。

无论如何,您希望更改newFile函数以返回文件名,而不是文件对象。然后,呼叫者将得到您可以open的内容。


当我们在做的时候:一旦你从一个函数回来,这个函数就完成了。您放在return之后的任何代码都不会运行。这意味着您永远不会关闭文件。这将导致多个问题。

首先,在Windows上,您可能无法open相同的文件名,而您仍然可以打开它。

而且,即使可以,您也可能看不到write到文件的内容。由于磁盘比 CPU 慢得多,因此当您写入文件时,它通常会被缓冲,稍后在磁盘赶上时写入。除非您close文件(或flush文件),否则数据可能尚未写入。

因此,您希望将f.close()移动到return之前

或者,更好的是,使用with语句,以确保文件在您完成操作后自动关闭。


所以:

def newFile():
# asks user for filename
filename = input("Insert 'filename.txt' Here >>> ")
# opens user inputted filename ".txt" and (w+) makes new and writes
with open(filename, 'w+') as f:
# asks for user input to enter into the file
usrInput = input("user input >>> ")
# writes user input to the file and adds new line
f.write(usrInput)
f.write("n")
return filename
# copy contents and outputs to new file
def copyToNew(f):
with open(f, "r") as oldFile:
fileContents = oldFile.read()
print("n",fileContents)
# needs to asks user if they would like to copy file to new document
print(f"Would you like to copy this (name{oldFile})? Y or N")
usrInput = input("Y or N >>> ")
print(usrInput)
if usrInput.lower() in {"y"}:
print("Your file has been created.")
elif usrInput.lower() in {"n"}:
print("Goodbye.")
else:
copyToNew(f)

最新更新