Python 如何从 .txt 文件中删除空行
声明:本页面是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
How to delete empty lines from a .txt file
提问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?
回答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)