【问题标题】:Delete blank rows from CSV?从 CSV 中删除空白行?
【发布时间】: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


【解决方案1】:

我也有同样的问题。

我将 .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)

【讨论】:

    【解决方案2】:

    将 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)
    

    【讨论】:

      【解决方案3】:

      使用 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
      【解决方案4】:

      这是一个使用 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)
      

      【讨论】:

        【解决方案5】:

        使用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 any(row):
        

        如果您还想将仅包含空格的字段视为空,您可以将其替换为:

        if any(field.strip() for field in row):
        

        请注意,在 Python 2.x 及更早版本中,csv 模块需要二进制文件, 所以你需要用 e 'b' 标志打开你的文件。在 3.x 中,这样做会 导致错误。

        【讨论】:

        • 呵呵,如果你使用if row.strip()
        • 感谢 LG,这对我有用。虽然我也有一些带有空白字段的行。例如:',,,,,\n'。如何使用 csv 模块检查空白行和带有空白字段的行。
        • @noskio @Paulo:空行可能是 csv 文件中非空行的一部分。例如:'foo, "bar\n\nbaz", quux' 有一个空行,但是是一个 csv 行。
        • any(row) 应该和any(field for field in row) 一样工作
        • @Laurence Gonsalves:这个答案有一个主要问题:文件应该以二进制模式(Python 2.X)打开,否则在 Windows 上,CR LF 处理会弄乱结果
        【解决方案6】:

        用 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)
        

        【讨论】:

          【解决方案7】:

          我需要这样做,但不幸的是,CSV 文件的末尾没有像这段代码那样写一个空白行(如果你保存-> .csv,Excel 也会这样做)。我使用 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:
          【解决方案8】:

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

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

          【讨论】:

          • Pandas 的库太大,无法仅用于这种情况。如果您已经将 pandas 用于其他东西,那么这可能是可行的选择。
          【解决方案9】:

          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
          

          【讨论】:

            【解决方案10】:

            在此脚本中,所有 CR / CRLF 都从 CSV 文件中删除,然后具有如下行:

            "My name";mail@mail.com;"This is a comment.
            Thanks!"
            

            执行脚本https://github.com/eoconsulting/lr2excelcsv/blob/master/lr2excelcsv.py

            结果(Excel CSV 格式):

            "My name",mail@mail.com,"This is a comment. Thanks!"
            

            【讨论】:

              【解决方案11】:

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

              编辑:一个真正的空行会像 '\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.rename),帮助(os.unlink))

              EDIT2:Laurence Gonsalves 让我注意到一个有效的 csv 文件可能在引用的 csv 字段中嵌入了空白行,例如1, 'this\n\nis tricky',123.45。在这种情况下, csv 模块将为您处理这些问题。对不起,劳伦斯,你的回答值得被接受。 csv 模块还将解决对"","",""\n 之类的行的担忧。

              【讨论】:

              • 好的。如何检查一行是否为空白?我正在寻找代码,请
              • 谢谢保罗。我的 csv 中同时存在这两种情况。像上面提到的那样,空白行和行中的所有空白字段。现在,与 csv 模块相比,使用您的方法的优点/缺点是什么?
              • @debugged:在赞成的答案中描述的 csv 方法不会删除所有空白字段的行。如果您只是过滤掉空白,那么 csv 模块似乎有点过头了。如果您要进行进一步操作,请使用 csv 模块,因为它将每个 csv 行拆分为一个方便的 python 列表。
              • 好东西!感谢您的回答保罗。感谢您的具体和详细。
              • 这个答案为了简单而牺牲了正确性。是的,使用 csv 模块稍微复杂一些,但它实际上适用于嵌入引用字段中的换行符等情况。
              猜你喜欢
              • 1970-01-01
              • 2014-07-27
              • 1970-01-01
              • 2018-06-07
              • 1970-01-01
              • 2022-01-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多