尝试写入文本文件时出现错误代码

问题描述 投票:-2回答:1

基本上我几天前就开始使用Python,并希望创建一个可以读写文件的程序。问题是我收到此错误:io.UnsupportedOperation:不可写

choice = input("Open / Create file: ")
if choice == 'Create' or choice == 'create':
    new_file_name = input("Create a name for the file: ")
    print(open(new_file_name, "w"))
    text = input("Type to write to file: \n")
    file2 = open(new_file_name)
    print(file2.write(text))
    print("Reading file...")
    print(open(new_file_name, "r"))
    print(file2.read())
elif choice == 'Open' or choice == 'open':
    filename = input("File name or directory: ")
    file = open(filename)
    open(filename, "r")
    time.sleep(1)
    print("Reading file...")
    time.sleep(1)
    print(file.read())
    choice2 = input("Write to file? Y/N \n")
    if choice2 == 'Y' or choice2 == 'y':
        text2 = input("Type to write to file: ")
        open(filename, "w")
        file = open(filename)
        file.write(text2)
        choice3 = input("Read file? Y/N ")
        if choice3 == 'Y' or choice3 == 'y':
            print(file.read())
python python-3.x read-write
1个回答
1
投票

您从代码中发布进度报告的想法很好,特别是在开始阶段。但似乎你不太了解它们之间的区别

print(open(new_file_name, "w"))

这是你的代码实际上做的,和

print(f'open("{new_file_name}", "w")')

我相信其中的第二个是你打算做的:打印

open("myfile.txt", "w")

但是你的实际代码所做的是(1)创建一个用于写入的打开文件对象,然后(2)将其类型和内存位置打印到屏幕上,最后(3)抛弃它。

因此,第一个解决方案是取出print()调用,或者至少将它们减少到print("step 1")等,直到你知道如何正确地执行它。

第二个修复是不通过尝试读取文件来响应Create的选择。如果用户正在创建文件,那么他们显然对任何先前版本的内容不感兴趣。你的代码通过阅读文件来响应Create,这似乎是对我来说,并且通常程序应该像普通用户(例如我)一样直观地思考。这是执行Create位的正确方法:

choice = input("Open / Create file: ")
if choice == 'Create' or choice == 'create':
    new_file_name = input("Create a name for the file: ")
    with open(new_file_name, "w") as file2:
        file2.write("This is stuff to go into the created file.\n")
else:
    ...

这会询问文件的名称,打开它进行写入,然后将一些内容写入其中。

© www.soinside.com 2019 - 2024. All rights reserved.