繁体   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