簡體   English   中英

如何從打開的文件中讀取?

[英]How do I read from an open file?

我正在嘗試編寫一個程序,可以將文件的內容存儲到用戶選擇的變量中。 例如,用戶會選擇一個位於當前目錄中的文件,然后選擇他們想要存儲它的變量。這是到目前為止我的代碼的一部分。

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方法。

這是您的代碼的修復:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM