Python - 删除字符数少于 "x" 的行,同时保留空行

Python - Remove line with less than "x" number of characters while preserving blank lines

我正在打开一个包含列和行的文本文件。有些行的字符比其他行多,我试图删除只有 <# 个字符的行。

该文件还包含一些我需要保留在文件中的空白间隔行。

with open(outfile) as f, open(outfile2,'w') as f2:
     for x in f:
           if (':') not in x and (',') not in x:
               newline=x.strip()+'\n'
               if len(newline.rstrip()) >= 43:
                   f2.write(newline)

第一个 if-statement 去除了文件中我不需要的一些文本行,同时还添加了我需要的额外间隔行。第二个 if-statement 尝试删除具有 <# 个字符的数据行,但此命令也删除了我需要保留的那些空白间隔行。如何在保留间隔行的同时摆脱那些包含 <# of characters 的行?

使用以下综合方法:

with open(outfile) as f, open(outfile2, 'w') as f2:
    for line in f:
        line = line.strip()
        if not line or (':' not in line and ',' not in line and len(line) >= 43):
            f2.write(line + '\n')

关键的 if 语句允许 写入 空行或满足所需条件的行。

with open(outfile) as f, open(outfile2,'w') as f2:
     for x in f:
           if not x.strip().replace("\n",""):
              f2.write(x)
              continue
           elif (':') not in x and (',') not in x:
               newline=x.strip()+'\n'
               if len(newline.rstrip()) >= 43:
                   f2.write(newline)

我想这个额外的 if 语句可以解决您的问题。如果没有,您可以创建一个条件语句的变体。