简体   繁体   中英

How do I read from an open file?

I'm trying to write a program that can store the contents of a file into a variable chosen by the user. For example, the user would choose a file located in the current directory and would then choose the variable they wanted to store it in. This is a segment of my code so far.

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")

When I input that loadfile = list1.antonio (which is an existing file) and whichvariable = list_1 it throws me this error:

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'

I have tried all sorts of things and I haven't find a solution.

You need to store result of open into a variable, and do read method from that variable.

Here the fix of your code:

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")

Dont forget to close your loadfile opened file.

And better

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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