从 CSV 中删除空行? [英] Delete blank rows from 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()
这样可以吗,或者有更好的方法吗?
Is this ok or is there a better way to do this?
推荐答案
使用 csv
模块:
import csv
...
with open(in_fnam) as in_file:
with open(out_fnam, 'w') as out_file:
writer = csv.writer(out_file)
for row in csv.reader(in_file):
if row:
writer.writerow(row)
如果您还需要删除所有字段都为空的行,请将 if row:
行更改为:
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):
<小时>
请注意,在 Python 2.x 及更早版本中,csv
模块需要二进制文件,所以你需要用 e 'b'
标志打开你的文件.在 3.x 中,这样做会导致错误.
Note that in Python 2.x and earlier, the csv
module expected binary files,
and so you'd need to open your files with e 'b'
flag. In 3.x, doing this will
result in an error.
这篇关于从 CSV 中删除空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!