如何读取打开的文件?

2024-09-30 16:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个程序,可以将文件的内容存储到用户选择的变量中。例如,用户将选择一个位于当前目录中的文件,然后选择要存储该文件的变量。到目前为止,这是我的一段代码

print("What .antonio file do you want to load?")
loadfile = input("")
open(loadfile, "r")

print("Which variable do you want to load it for? - list_1, list_2, list_3")
whichvariable = input("") 

if whichvariable == "list_1":
    list_1 = loadfile.read()
elif whichvariable == "list_2":
    list_2 = loadfile.read()
elif whichvariable == "list_3":
    list_3 = loadfile.read()
else:
    print("ERROR")

当我输入loadfile = list1.antonio(这是一个现有的文件)和whichvariable = list_1时,它会抛出以下错误:

Traceback (most recent call last):
  File "D:\Antonio\Projetos\Python\hello.py", line 29, in <module>
    list_1 = loadfile.read()
AttributeError: 'str' object has no attribute 'read'

我试过各种各样的方法,但都没有找到解决办法


Tags: 文件to用户youreadinputloaddo
1条回答
网友
1楼 · 发布于 2024-09-30 16:34:52

您需要将open的结果存储到一个变量中,并从该变量执行read方法

下面是代码的修复:

print("What .antonio file do you want to load?")
loadfile = input("")
loadfile = open(loadfile, "r") # you forget to store the result of open into loadfile

print("Which variable do you want to load it for? - list_1, list_2, list_3")
whichvariable = input("") 

if whichvariable == "list_1":
    list_1 = loadfile.read()
elif whichvariable == "list_2":
    list_2 = loadfile.read()
elif whichvariable == "list_3":
    list_3 = loadfile.read()
else:
    print("ERROR")

别忘了关闭loadfile打开的文件

更好

print("What .antonio file do you want to load?")
loadfile = input("")
with open(loadfile, "r") as openedfile:

    print("Which variable do you want to load it for? - list_1, list_2, list_3")
    whichvariable = input("") 

    if whichvariable == "list_1":
        list_1 = loadfile.read()
    elif whichvariable == "list_2":
        list_2 = loadfile.read()
    elif whichvariable == "list_3":
        list_3 = loadfile.read()
   else:
       print("ERROR")

相关问题 更多 >