python - 从 CSV 中删除空白行?

标签 python csv delete-row

我有一个大的 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/

相关文章:

sql - 要删除,更改实体的标志 VS 移动到另一个表?

python - 使用Python进行Elasticsearch多重查询/搜索

Python3如何安装.ttf字体文件?

python - numpy 读取带有复数的 .csv

C# 将 csv 转换为 xls(使用现有的 csv 文件)

excel - 检查特定列中的文本后删除行

python - 如果将列表附加到自身会发生什么?

python - python 中的嵌套列表和 for 循环程序给了我一个疯狂的结果

python-3.x - tensorflow : Using Queue for CSV file with custom Estimator and "input_fn" function

java - 使用java删除文本文件中的一行