如何从.txt文件中删除空行

时间:2016-06-07 15:03:04

标签: python

我有一个巨大的输入.txt这种形式的文件:

0 1 0 1 0 0 0 0 0 0

0 1 0 1 0 0 0 0 0 0

0 1 0 1 0 0 0 0 0 0

我想删除所有空行,以便创建一个新的输出.txt文件,如下所示:

0 1 0 1 0 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0

我尝试使用grep:

grep -v '^$' test1.txt > test2.txt 

但我得到" SyntaxError:语法无效"

当我按照某人的建议使用pandas时,我得到不同数量的列,并且一些整数被转换为浮点数:例如:1.0而不是1

当我按照督察G4dget的建议(见下文)时,它很好用,只有一个问题:最后一行没有完全打印出来:

with open('path/to/file') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        if not line.strip(): continue  # skip the empty line
        outfile.write(line)  # non-empty line. Write it to output

它必须与我的文件有关...

我已经在下面(和其他人)处理了类似的帖子,但是我的情况并不合适,主要是由于上述原因

How to delete all blank lines in the file with the help of python?

one liner for removing blank lines from a file in python?

2 个答案:

答案 0 :(得分:10)

我就是这样做的:

with open('path/to/file') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        if not line.strip(): continue  # skip the empty line
        outfile.write(line)  # non-empty line. Write it to output

答案 1 :(得分:0)

您可以使用strip();

for line in yourTxtFile:
   if not line.strip():
      # write new file
      print (line)
相关问题