例如,我们有一些这样的文件:
first line
second line
third line
结果我们必须得到:
first line
second line
third line
只使用蟒蛇
例如,我们有一些这样的文件:
first line
second line
third line
结果我们必须得到:
first line
second line
third line
只使用蟒蛇
该with
语句非常适合自动打开和关闭文件。
with open('myfile','rw') as file:
for line in file:
if not line.isspace():
file.write(line)
import fileinput
for line in fileinput.FileInput("file",inplace=1):
if line.rstrip():
print line
import sys
with open("file.txt") as f:
for line in f:
if not line.isspace():
sys.stdout.write(line)
另一种方法是
with open("file.txt") as f:
print "".join(line for line in f if not line.isspace())
我知道你问过 Python,但你对 Win 和 Linux 的评论表明你追求的是跨平台性,而 Perl 至少和 Python 一样跨平台。您可以在命令行上使用一行 Perl 轻松完成此操作,无需脚本:perl -ne 'print if /\S/' foo.txt
(我喜欢 Python 并且 99% 的时间都喜欢它而不是 Perl,但有时我真的希望我可以像使用 -e 切换到 Perl 一样使用它来编写命令行脚本!)
也就是说,以下 Python 脚本应该可以工作。如果您希望经常这样做或对大文件执行此操作,则也应通过编译正则表达式对其进行优化。
#!/usr/bin/python
import re
file = open('foo.txt', 'r')
for line in file.readlines():
if re.search('\S', line): print line,
file.close()
有很多方法可以做到这一点,这只是一种:)
with open(fname, 'r+') as fd:
lines = fd.readlines()
fd.seek(0)
fd.writelines(line for line in lines if line.strip())
fd.truncate()
>>> s = """first line
... second line
...
... third line
... """
>>> print '\n'.join([i for i in s.split('\n') if len(i) > 0])
first line
second line
third line
>>>
您是否尝试过类似下面的程序?
for line in open(filename):
if len(line) > 1 or line != '\n':
print(line, end='')
您可以使用以下方式删除所有空行:
with open("new_file","r") as f:
for i in f.readlines():
if not i.strip():
continue
if i:
print i,
我们还可以使用以下方式将输出写入文件:
with open("new_file","r") as f, open("outfile.txt","w") as outfile:
for i in f.readlines():
if not i.strip():
continue
if i:
outfile.write(i)
说明:在基于 Linux/Windows 的平台上,我们安装了以下解决方案的 shell,因为“os”模块将可用并尝试使用 Regex
解决方案:
import os
os.system("sed -i \'/^$/d\' file.txt")