从CSV中删除空白行? [英] Delete blank rows from CSV?
本文介绍了从CSV中删除空白行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大的csv文件,其中一些行是完全空白的。如何使用Python从csv中删除所有空白行?
I have a large csv file in which some rows are entirely blank. How do I use Python to delete all blank rows from the csv?
在所有的建议之后,这是我到目前为止
After all your suggestions, this is what I have so far
import csv
# open input csv for reading
inputCSV = open(r'C:\input.csv', 'rb')
# create output csv for writing
outputCSV = open(r'C:\OUTPUT.csv', 'wb')
# prepare output csv for appending
appendCSV = open(r'C:\OUTPUT.csv', 'ab')
# create reader object
cr = csv.reader(inputCSV, dialect = 'excel')
# create writer object
cw = csv.writer(outputCSV, dialect = 'excel')
# create writer object for append
ca = csv.writer(appendCSV, dialect = 'excel')
# add pre-defined fields
cw.writerow(['FIELD1_','FIELD2_','FIELD3_','FIELD4_'])
# delete existing field names in input CSV
# ???????????????????????????
# loop through input csv, check for blanks, and write all changes to append csv
for row in cr:
if row or any(row) or any(field.strip() for field in row):
ca.writerow(row)
# close files
inputCSV.close()
outputCSV.close()
appendCSV.close()
这是确定还是有更好的方法? / p>
Is this ok or is there a better way to do this?
推荐答案
使用 csv
模块:
import csv
...
input = open(in_fnam, 'rb')
output = open(out_fnam, 'wb')
writer = csv.writer(output)
for row in csv.reader(input):
if row:
writer.writerow(row)
input.close()
output.close()
需要删除所有字段都为空的行,将如果行:
行更改为:
If you also need to remove rows where all of the fields are empty, change the if row:
line to:
if any(row):
只有空格为空,你可以替换为:
And if you also want to treat fields that consist of only whitespace as empty you can replace it with:
if any(field.strip() for field in row):
这篇关于从CSV中删除空白行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文