使用Python从文件中删除空格和空行 [英] Removing spaces and empty lines from a file Using Python
本文介绍了使用Python从文件中删除空格和空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件,其中包含一个值2000,00.
I have a file which contains a value 2000,00.
但是它包含2000,00之后的空格和空行.
But it contains spaces after 2000,00 and empty lines.
我想删除所有空格和空白行,如果有人可以提出一些想法,我尝试了多种方法,但没有成功.
I want to remove all the spaces and empty lines, if some one can give some Idea, I ave tried a number of ways but no success.
我厌倦的一种方法如下
# 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()
推荐答案
strip()
删除前导和尾随空格字符.
strip()
removes leading and trailing whitespace characters.
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
.
Then you can redirect the script into a file python clean_number.py > file.txt
, for example.
这篇关于使用Python从文件中删除空格和空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文