简体   繁体   中英

How to use Python to read a txt file line by line within a particular range while ignoring empty lines?

I tried to read a txt file line by line for 10 lines, starting from a certain string, and ignoring empty lines. Here's the code I used:

a =[]

file1 = open('try2.txt', 'r')
for line in file1:
    if line.startswith('Merl'):
        for line in range(10):
            if line != '\n':
                a.append(next(file1))

print(a)

But the output still included empty lines. Any suggestions please?

The problem occures because you check if line equals '\n' but you append the next line. The solution will be to append the current line, and then call next(file1) .

a = []
file1 = open('try2.txt', 'r')
for line in file1:
    if line.startswith('Merl'):
        for i in range(10):
            if line != '\n':
                a.append(line)
                line = next(file1)

print(a)

If I understood correctly you only wanted to look at the first 10 lines or? Then try the following:

a = []
file1 = open('try2.txt', 'r')

counter = 0
for line in file1:
    counter +=1
    if counter > 10:
        break
    if line.startswith('Merl'):
        if line != '\n':
            a.append(next(file1))

print(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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