我有一个大的 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
模块:
import csv
...
with open(in_fnam, newline='') as in_file:
with open(out_fnam, 'w', newline='') as out_file:
writer = csv.writer(out_file)
for row in csv.reader(in_file):
if row:
writer.writerow(row)
如果您还需要删除所有字段为空的行,请将 if row:
行更改为:
if any(row):
如果您还想将仅包含空格的字段视为空,您可以将其替换为:
if any(field.strip() for field in row):
请注意,在 Python 2.x 及更早版本中,csv
模块需要二进制文件,因此您需要使用 e 'b'
标志。在 3.x 中,这样做会导致错误。
关于python - 从 CSV 中删除空白行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4521426/