Python 如何从 .t​​xt 文件中删除空行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37682955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:47:30  来源:igfitidea点击:

How to delete empty lines from a .txt file

python

提问by Lucas

I have a huge input .txt file of this form:

我有一个巨大的这种形式的输入 .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

and I want to delete all empty lines in order to create a new output .txt file like this:

我想删除所有空行以创建一个新的输出 .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

I tried doing it with grep:

我尝试用 grep 来做:

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

but I get "SyntaxError: invalid syntax"

但我得到“语法错误:语法无效”

When I do it with pandas as someone suggests, I get different number of columns and some integers are converted into floats: e.g.: 1.0 instead of 1

当我按照某人的建议用熊猫做这件事时,我得到了不同数量的列,一些整数被转换为浮点数:例如:1.0 而不是 1

When I do it as inspectorG4dget suggests (see below), it works nice, with only 1 problem: the last line is not printed completely:

当我按照inspectorG4dget的建议进行操作时(见下文),效果很好,只有一个问题:最后一行没有完全打印:

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

It must be something with my file then...

那一定是我的文件有问题......

I've already addressed similar posts like these below (and others), but they are not working in my case, mainly due to the reasons explained above

我已经在下面(和其他人)写过类似的帖子,但它们在我的情况下不起作用,主要是由于上面解释的原因

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

如何借助python删除文件中的所有空行?

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

一个用于从 python 中的文件中删除空行的衬垫?

回答by inspectorG4dget

This is how I would do it:

这就是我将如何做到的:

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

回答by erolkaya84

You can use strip();

您可以使用 strip();

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