简体   繁体   English

如何遍历 python 中的连续行?

[英]How to loop through consecutive lines in python?

I have a text file that, for the sake of simplicity, contains:为了简单起见,我有一个文本文件,其中包含:

cat
dog
goat
giraffe
walrus
elephant

How can I create a script that would set a variable, animal in this case, to the first line in the text file, print animal, but then do the whole thing again, but make animal set to the next line (in this instance, dog).如何创建一个脚本,将变量设置为在这种情况下为animal,到文本文件的第一行,打印animal,然后再次执行整个操作,但将animal设置为下一行(在这种情况下,狗)。

Here's what I've tried so far:这是我到目前为止所尝试的:

while True:
    with open('./text.txt','r') as f:
        for i in enumerate('./text.txt'):
            if i in lines:
                print(lines)

Use readlines to store each line in a list.使用 readlines 将每一行存储在一个列表中。

with open('file.txt','r') as f:
    animals = f.readlines()

for animal in animals:
    print(animal.strip())

You could try the following:您可以尝试以下方法:

with open('./text.txt') as f:
    for animal in f.readlines():
        print(animal.strip())

If you want to read the file one line at a time (which may be needed for large files):如果您想一次读取一行文件(大文件可能需要):

with open('./text.txt','r') as f:
    line = True
    # this will stop when there is nothing left to read, as line will be ''
    # note that an 'empty' line will still have a line ending, i.e. '\n'
    while line:
        line = f.readline()
        print(line)

If you don't care about the size, you can read all lines at once with .readlines() and just loop over the returned values from that.如果您不关心大小,则可以使用.readlines()一次读取所有行,然后循环从中返回的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM