提问人:always-confused 提问时间:4/22/2019 最后编辑:always-confused 更新时间:4/22/2019 访问量:54
如何使用枚举将文件的特定行读取为 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
答案可能非常明显,我没有看到它,但所有解决方案都将不胜感激。
答:
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 = i
account = line
评论
account = line
??account = i
print(account)
1