我对编程非常陌生,我已责成自己编写一个无用的程序,以帮助学习如何编写本书中没有的某些功能代码。该程序的目的是使用用户输入的文件名编写文件,然后将内容添加到文件中。我已经做到了。我遇到的问题来自程序的后半部分。
第二部分假设是要读取您刚刚创建的文件的内容。然后询问您是否要将内容复制到新文件。然后为新文件分配一个用户输入的名称,并复制原始文件的内容。
我在读取旧文件名时遇到问题。而且我从程序中得到的输出看起来像这样:
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()
答案 0 :(得分:0)
问题在这里:
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()
移到{em> 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)