簡體   English   中英

如何使用枚舉將文件的特定行讀取到python中的變量?

[英]How to read a specific line of a file to a variable in python using enumerate?

在python中,我有一小段代碼,它接受整數輸入並讀取文件,轉到輸入的行並將該行讀取到變量。 但是,在檢查以確保為變量分配了正確的內容時,用戶輸入的數字被分配給變量,而不是該行上的變量。

我查看了與此非常相似的帖子,並使用這些代碼片段來創建它。

到目前為止我所擁有的是以下內容:

    with open("accounts.txt") as f:
        for i, line in enumerate(f):
            if i == Access:
                account = i
                break

# 'Access' is an integer, such as 1
# print(account) returns that integer rather than the string on that line in the file

答案可能非常明顯,我沒有看到,但所有解決方案都將受到贊賞。

account = i應該是account = line

print(account) returns that integer rather than the string on that line in the file因為您正在打印循環的迭代而不是行本身。

你只需要用account = line替換account = i就可以了。

暫無
暫無

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

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