简体   繁体   English

如何使用 Python 在特定范围内逐行读取 txt 文件,同时忽略空行?

[英]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.我尝试逐行读取一个 txt 文件 10 行,从某个字符串开始,并忽略空行。 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.但是 output 仍然包含空行。 Any suggestions please?有什么建议吗?

The problem occures because you check if line equals '\n' but you append the next line.出现问题是因为您检查line是否等于'\n'但您 append 是下一行。 The solution will be to append the current line, and then call next(file1) .解决方案将是 append 当前行,然后调用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?如果我理解正确的话,你只想看前 10 行或者? 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)

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

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