所以我的文本文件格式如下:
a
b
c
我知道如何strip()
和rstrip()
,但我想摆脱空行。
我想让它更短:
a
b
c
答案 0 :(得分:3)
您可以使用fileinput
module从命令行中的stdin和/或文件中删除所有空白行(仅包含空格的行):
#!/usr/bin/env python
import sys
import fileinput
for line in fileinput.input(inplace=True):
if line.strip(): # preserve non-blank lines
sys.stdout.write(line)
答案 1 :(得分:1)
您可以使用正则表达式:
import re
txt = """a
b
c"""
print re.sub(r'\n+', '\n', txt) # replace one or more consecutive \n by a single one
但是,不会删除带空格的行。更好的解决方案是:
re.sub(r'(\n[ \t]*)+', '\n', txt)
这样,你也会删除前导空格。
答案 2 :(得分:0)
只需删除任何仅等于" \ n":
的行in_filename = 'in_example.txt'
out_filename = 'out_example.txt'
with open(in_filename) as infile, open(out_filename, "w") as outfile:
for line in infile.readlines():
if line != "\n":
outfile.write(line)
如果您只想更新同一个文件,请关闭并重新打开它以使用新数据覆盖它:
filename = 'in_example.txt'
filedata = ""
with open(filename, "r") as infile:
for line in infile.readlines():
if line != "\n":
filedata += line
with open(filename, "w") as outfile:
outfile.write(filedata)