我正在尝试编写一个程序,可以将文件的内容存储到用户选择的变量中。例如,用户将选择一个位于当前目录中的文件,然后选择要存储该文件的变量。到目前为止,这是我的一段代码
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'
我试过各种各样的方法,但都没有找到解决办法
您需要将open的结果存储到一个变量中,并从该变量执行
read
方法下面是代码的修复:
别忘了关闭
loadfile
打开的文件更好
相关问题 更多 >
编程相关推荐