使用Python从csv中删除线也添加了一行 [英] Removing lines from a csv with Python also adds an extra line
本文介绍了使用Python从csv中删除线也添加了一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这段代码,从stackoverflow的另一个地方借用,删除所有的csv有无写在其中的地方。但是,它还向csv添加了一行。如何更改此代码以删除该额外行?我认为问题是由 inplace
引起的,但是当我采用 inplace
时,文件不再通过运行码。
This code, borrowed from another place on stackoverflow, removes all of the places that the csv has "None" written in it. However, it also adds an extra line to the csv. How can I change this code to remove that extra line? I think the problem is caused by inplace
, but when I take inplace
away the file is no longer altered by running the code.
def cleanOutputFile(filename):
for line in fileinput.FileInput(filename,inplace=1):
line = line.replace('None',"")
print line
谢谢!
推荐答案
如果要替换所有无
:
with open(filename) as f:
lines = f.read().replace("None","")
with open(filename,"w") as f1:
f1.write(lines)
使用 rstrip
和 fileinput
也应该可以工作:
Using rstrip
with fileinput
should also work:
import fileinput
for line in fileinput.FileInput(fileinput,inplace=1):
print line.replace('None',"").rstrip() # remove newline character to avoid adding extra lines in the output
这篇关于使用Python从csv中删除线也添加了一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文