简体   繁体   English

如何删除txt文件中的“空”行

[英]How to delete 'empty' lines in txt file

I think I've tried everything to make it work but I still can't get the results I want.我想我已经尽了一切努力让它发挥作用,但我仍然无法得到我想要的结果。 I basically want to delete empty lines in txt file that my other script created.我基本上想删除我的其他脚本创建的 txt 文件中的空行。 I've tried: .isspace(), deleting lines with n amount of spaces, deleting lines with '\n'.我试过:.isspace(),删除带有 n 个空格的行,删除带有 '\n' 的行。 None of these worked can you guys help me?这些都不行,你们能帮帮我吗? Here is part of txt file and my code:这是txt文件的一部分和我的代码:

Gmina Wiejska
 Urząd Gminy Brzeziny 
 

 

 ul. Sienkiewicza 16a 95-060 Brzeziny
Łącko
Gmina Wiejska
 Urząd Gminy Łącko 


Łącko 445 33-390 Łącko
Węgliniec
Gmina Miejsko-wiejska
 Urząd Gminy i Miasta Węgliniec 


ul. Sikorskiego 3 59-940 Węgliniec```

code:代码:

delete = ['<td align="center" class="top" colspan="3"><b>',
          '</td>',
          '<br/></b></td>',
          '<br/></b>',
          'None',
          'brak',
          '[]',
          '\n'
          ]
with open('/Users/dominikgrzeskowiak/python/gminy/text/text1.txt','r+') as file:
    for line in file:
        print(a)
        for i in delete:
            line = line.replace(i,'')
            print(i)
        print(line)  
        if line != '  ' or line != ' \n' or line != '   ':  
            with open('/Users/dominikgrzeskowiak/python/gminy/text/text2.txt','a') as f:
                f.write(line+'\n')

Just check if the line is not empty after removing blanks with stripstrip删除空格后只需检查该行是否为空

with open('text1.txt', 'r+', encoding='utf-8') as file, open('text2.txt', 'a', encoding='utf-8') as f:
    for line in file:
        if line.strip():
            f.write(line)

You should open text2 once, not every line in the text1 .您应该打开text2一次,而不是text1中的每一行。

You could use regex for searching patterns您可以使用正则表达式来搜索模式

import re


with open('somefile.txt','r') as file:
    txt = file.readlines()for i in txt:
    if re.fullmatch("\\s*",i):
        continue
    print(i,end="")

but you could do it with pure python too但你也可以用纯 python

with open('somefile.txt','r') as file:
     txt = file.readlines()
     for i in txt:
         if i.strip() == '':
              continue
      print(i, end='')

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

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