我正在尝试编写一个程序,该程序可以将文件的内容存储到用户选择的变量中。例如,用户将选择一个位于当前目录中的文件,然后选择他们想要存储在其中的变量。这是到目前为止我的代码的一部分。
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'
我尝试了各种各样的方法,但没有找到解决方案。
答案 0 :(得分:-1)
您需要将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")