【发布时间】:2011-05-30 02:48:00
【问题描述】:
我有一个大的 csv 文件,其中一些行完全是空白的。如何使用 Python 从 csv 中删除所有空白行?
根据您的所有建议,这就是我目前所拥有的
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()
这样可以吗?或者有更好的方法吗?
【问题讨论】:
-
为什么文件是 CSV 文件这一事实是相关的?
-
只看使用csv模块是否比不使用它有显着优势。
-
使用 csv 模块具有 Laurence Gonsalves 概述的一个主要优势:当输入文件在引用的 csv 字段中嵌入空行时。
-
你的意思是像 '','','','' ?我该如何检查呢?另外,如何删除特定行。说出文件中的第一行或第五行。
-
@debugged: 接受的答案有一个主要问题:文件应该以二进制模式(Python 2.X)打开,否则在 Windows 上,CR LF 处理会弄乱结果。
标签: python csv delete-row