如何使用枚举将文件的特定行读取为 python 中的变量?

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

提问人:always-confused 提问时间:4/22/2019 最后编辑:always-confused 更新时间:4/22/2019 访问量:54

问:

在 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

答案可能非常明显,我没有看到它,但所有解决方案都将不胜感激。

python-3.x 文件 枚举

评论

1赞 Rakesh 4/22/2019
account = line??
0赞 DirtyBit 4/22/2019
因为会给你account = iprint(account)1
2赞 John Coleman 4/22/2019
“答案可能很明显,我没有看到它,”---是的。我认为这应该作为一个简单的错别字关闭。
0赞 Valentino 4/22/2019
你好!您不应该“关闭”编辑标题的问题。相反,接受你认为最有用的答案。请观看导览,快速了解 stackoverflow 的工作原理,并阅读当有人回答时该怎么做

答:

0赞 Frederik Bode 4/22/2019 #1

account = i应该是account = line

0赞 Avi Thour 4/22/2019 #2

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

你只需要替换成,你就会被读出去。account = iaccount = line