Home > front end >  How to use Python to read a txt file line by line within a particular range while ignoring empty lin
How to use Python to read a txt file line by line within a particular range while ignoring empty lin

Time:10-12

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?

CodePudding user response:

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)

CodePudding user response:

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)
  • Related