[英]How to read a specific line of a file to a variable in python using enumerate?
In python I have a small piece of code that takes an integer input and reads through a file, going to the line inputted and reading that line to a variable. 在python中,我有一小段代码,它接受整数输入并读取文件,转到输入的行并将该行读取到变量。 However, when checking to make sure the correct thing was assigned to the variable, the number that was inputted by the user was assigned to the variable, not what was on the line.
但是,在检查以确保为变量分配了正确的内容时,用户输入的数字被分配给变量,而不是该行上的变量。
I have looked through posts that are quite similar to this and have used those pieces of code to create this. 我查看了与此非常相似的帖子,并使用这些代码片段来创建它。
What I have so far is the following: 到目前为止我所拥有的是以下内容:
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
The answer is probably very obvious and I'm not seeing it, but all solutions would be appreciated. 答案可能非常明显,我没有看到,但所有解决方案都将受到赞赏。
account = i
应该是account = line
print(account) returns that integer rather than the string on that line in the file
because you are printing the iteration of the loop rather than the line itself. print(account) returns that integer rather than the string on that line in the file
因为您正在打印循环的迭代而不是行本身。
You just need to replace account = i
with account = line
and you are read to go. 你只需要用
account = line
替换account = i
就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.