从CSV文件中删除空行?

30

我有一个大的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文件的事实为什么相关呢? - Robert Rossney
只是为了看看使用csv模块是否比不使用它有显著的优势。 - debugged
使用csv模块有一个主要优点,由Laurence Gonsalves概述:当输入文件中嵌入了带引号的csv字段的空行时。 - Paulo Scardine
你的意思是像这样'','','',''吗?我如何检查它呢?另外,我如何删除文件中的特定行,比如第一行或第五行? - debugged
@debugged:已接受的答案存在一个主要问题:文件应该在二进制模式下打开(Python 2.X),否则在Windows上,CR LF处理会破坏结果。 - John Machin
11个回答

39

使用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模块需要二进制文件,因此您需要使用'b'标志打开您的文件。在3.x中,这样做将导致错误。


4
如果你使用 if row.strip(),即使没有使用 csv 模块,同样的代码也可以工作。 - nosklo
4
@noskio @Paulo:在CSV文件中,可以有空白行作为非空行的一部分。例如:'foo, "bar\n\nbaz", quux'包含一个空白行,但是是单个CSV行。 - Laurence Gonsalves
1
any(row) 应该与 any(field for field in row) 的作用相同。 - jfs
4
这个回答有一个主要问题:文件应该在二进制模式下打开(Python 2.X),否则在Windows系统中,CR LF处理会破坏结果。 - John Machin
@radtek map不能添加或删除元素,只能修改元素。如果你想要比使用for循环更加功能化的方法,你可以使用filter或推导式。例如:res = [process_row(row) for row in reader if row]会删除空行并处理余下的行,用process_row进行处理。 - Laurence Gonsalves
显示剩余16条评论

11

惊讶于这里没有人提到pandas。这是一个可能的解决方案。

import pandas as pd
df = pd.read_csv('input.csv')
df.to_csv('output.csv', index=False)

Pandas是一个过于庞大的库,仅仅为了这个案例使用它有些浪费。如果你已经在其他方面使用Pandas,那么这可能是一个可行的选择。 - Aabesh Karmacharya

8

使用Python删除CSV文件中的空行

    import csv
  ...


 with open('demo004.csv') as input, open('demo005.csv', 'w', newline='') as output:
     writer = csv.writer(output)
     for row in csv.reader(input):
         if any(field.strip() for field in row):
             writer.writerow(row)

谢谢您


感谢您的@Dilip Kumar Choudhary。 - just don't be user123

5
使用pandas很简单。使用pandas打开csv文件:
import pandas as pd
df = pd.read_csv("example.csv")
#checking the number of empty rows in th csv file
print (df.isnull().sum())
#Droping the empty rows
modifiedDF = df.dropna()
#Saving it to the csv file 
modifiedDF.to_csv('modifiedExample.csv',index=False)

3

您需要打开第二个文件,将所有非空行写入其中,删除原始文件并将第二个文件重命名为原始名称。

编辑:真正的空行将会像'\n'一样:

for line in f1.readlines():
    if line.strip() == '':
        continue
    f2.write(line)

一行全为空字段的样子是 ',,,,,\n'。如果您认为这是一行空白行:
for line in f1.readlines():
    if ''.join(line.split(',')).strip() == '':
        continue
    f2.write(line)

打开、关闭、删除和重命名文件的操作留给您自己练习。(提示: 导入 os,使用 help(open),help(os.rename),help(os.unlink))

编辑2: Laurence Gonsalves提醒我,一个有效的csv文件可能会在引号括起来的csv字段中嵌入空行,例如1, 'this\n\nis tricky',123.45。在这种情况下,csv模块会为您处理。对不起Laurence,您的回答应该被接受。csv模块也会解决类似"","",""\n这样的问题。


好的。我该如何检查一行是否为空?请提供代码。 - debugged
谢谢保罗。我的csv文件中有两种情况。一是空行,二是像你上面提到的那样整行都是空字段。那么,使用您的方法与使用csv模块相比,有什么优缺点呢? - debugged
1
太棒了!感谢你的回答,Paulo。我很感激你的具体和详细解答。 - debugged
1
这个答案为简单性而放弃了正确性。是的,使用csv模块会稍微复杂一些,但对于像在引号字段中嵌入换行符这样的情况,它确实可以正常工作。 - Laurence Gonsalves
使用readlines是一种糟糕的做法。完全忽略文件是CSV文件也是如此。这个答案不应该被接受! - John Machin
显示剩余4条评论

2

这里有一个使用pandas的解决方案,可以删除空白行。

 import pandas as pd
 df = pd.read_csv('input.csv')
 df.dropna(axis=0, how='all',inplace=True)
 df.to_csv('output.csv', index=False)

2

使用Python代码从CSV文件中删除空行,而不创建另一个文件。

def ReadWriteconfig_file(file):

try:
    file_object = open(file, 'r')
    lines = csv.reader(file_object, delimiter=',', quotechar='"')
    flag = 0
    data=[]
    for line in lines:
        if line == []:
            flag =1
            continue
        else:
            data.append(line)
    file_object.close()
    if flag ==1: #if blank line is present in file
        file_object = open(file, 'w')
        for line in data:
            str1 = ','.join(line)
            file_object.write(str1+"\n")
        file_object.close() 
except Exception,e:
    print e

1

我需要这样做,但是不想在CSV文件的末尾写入空行,就像这段代码不幸地做了一样(如果你使用Excel保存为.csv格式,它也会这样做)。我的(更简单)使用CSV模块的代码也会这样做:

import csv

input = open("M51_csv_proc.csv", 'rb')
output = open("dumpFile.csv", 'wb')
writer = csv.writer(output)
for row in csv.reader(input):
    writer.writerow(row)
input.close()
output.close() 

M51_csv_proc.csv共有125行;程序总是输出126行,最后一行为空。

我已经浏览了所有这些线程,但似乎没有任何改变这种行为的方法。


为了避免“关闭”行,请尽量使用(在读取时):with open(filename) as in_file:为了避免在写入时添加冗余的\r或\n,请使用以下方式:with open(filename, 'w+', newline='') as out_file: - DarkLight

0

我也遇到了同样的问题。

我将 .csv 文件转换为数据框,然后再将数据框转换回 .csv 文件。

最初的带有空行的 .csv 文件是 'csv_file_logger2.csv'。

因此,我执行以下过程:

import csv
import pandas as pd
df=pd.read_csv('csv_file_logger2.csv')

df.to_csv('out2.csv',index = False)

0

将 PATH_TO_YOUR_CSV 替换为您的路径

import pandas as pd

df = pd.read_csv('PATH_TO_YOUR_CSV')
new_df = df.dropna()
df.dropna().to_csv('output.csv', index=False)

或者内联:

import pandas as pd

pd.read_csv('data.csv').dropna().to_csv('output.csv', index=False)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接