简体   繁体   English

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

[英]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.

相关问题 Python 2.7。 使用枚举读取一个文件以获取行号,并使用行号转到另一个文件 - Python 2.7. Read one file using enumerate to get line numbers and go to another file using line numbers Python-如何读取文本文件中的特定行? - Python - How to read a specific line in a text file? 从文本文件中读取特定行并使用Python 2.7分配给变量 - Read specific line from text file and assign to variable using Python 2.7 如何使用python读取特定行并在此行中打印特定位置 - how to read a specific line and print a specific position in this line using python 将文本文件的特定 int 行读取并获取到 python 上的变量中 - read and get specific int line of the text file into variable on python 如何使用python从文件读取当前行上方的特定行 - How to read a specific line which is above the current line from a file using python 当格式特定时,如何使用 Python 逐行读取文本文件 - how do i read a text file in line-by-line using Python when the formatting is specific 如何从文本文件中逐行读取变量并将其拆分 - how to read a variable line by line from a text file and split it python 使用python从文件中的特定行读取前几行 - read previous lines from specific line in a file using python Python:逐行读取文本变量(不是文件) - Python: read text variable line by line (not file)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM