繁体   English   中英

Python:用户输入要写入/写入的文件名。 程序然后打开/读取

[英]Python: User inputs filename to write/be written to. program then opens/reads

我对编程非常陌生,我已责成自己编写一个无用的程序,以帮助学习如何编写本书中没有的某些功能代码。 该程序的目的是使用用户输入的文件名编写文件,然后将内容添加到文件中。 我已经做到了。 我遇到的问题来自程序的后半部分。

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM