我有一个包含值2000,00的文件。
但它包含2000,00之后的空格和空行。
我想删除所有空格和空行,如果有人可以给出一些想法,我已经尝试了很多方法但没有成功。
我厌倦的一种方法如下
# Read lines as a list
fh = open("transfer-out/" + file, "r")
lines = fh.readlines()
fh.close()
# Weed out blank lines with filter
lines = filter(lambda x: not x.isspace(), lines)
# Write "transfer-out/"+file+".txt", "w"
fh = open("transfer-out/"+file, "w")
#fh.write("".join(lines))
# should also work instead of joining the list:
fh.writelines(lines)
fh.close()
答案 0 :(得分:6)
strip()
删除前导和尾随空白字符。
with open("transfer-out/" + file, "r") as f:
for line in f:
cleanedLine = line.strip()
if cleanedLine: # is not empty
print(cleanedLine)
然后,您可以将脚本重定向到文件python clean_number.py > file.txt
,例如。
答案 1 :(得分:3)
另一个有列表理解的人:
clean_lines = []
with open("transfer-out/" + file, "r") as f:
lines = f.readlines()
clean_lines = [l.strip() for l in lines if l.strip()]
with open("transfer-out/"+file, "w") as f:
f.writelines('\n'.join(clean_lines))
答案 2 :(得分:2)
更改“行”行以使用以下生成器,它应该可以解决问题。
lines = (line.strip() for line in fh.readlines() if len(line.strip()))
答案 3 :(得分:1)
这可以按你的意愿运作:
file(filename_out, "w").write(file(filename_in).read().strip())
编辑:虽然之前的代码在python 2.x中有效,但它不能正常运行python 3(请参阅@gnibbler注释)对于这两个版本都使用此代码:
open(filename_out, "w").write(open(filename_in).read().strip())
答案 4 :(得分:1)
功能一::)
import string
from itertools import ifilter, imap
print '\n'.join(ifilter(None, imap(string.strip, open('data.txt'))))
# for big files use manual loop over lines instead of join
用法:
$ yes "2000,00 " | head -n 100000 > data.txt
$ python -c "print '\n'*100000" >> data.txt
$ wc -l data.txt
200001 data.txt
$ python filt.py > output.txt
$ wc -l output.txt
100000 output.txt