6

我有一个包含值 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()
4

5 回答 5

8

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中,例如。

于 2012-05-29T06:44:31.770 回答
4

另一个具有列表理解的:

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))
于 2012-05-29T06:47:39.350 回答
2

更改您的“行”行以使用以下生成器,它应该可以解决问题。

lines = (line.strip() for line in fh.readlines() if len(line.strip()))
于 2012-05-29T06:51:23.143 回答
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())
于 2012-05-29T06:45:30.503 回答
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
于 2012-05-29T07:20:45.123 回答