【问题标题】:I have a CSV file with header. Want to remove first 5 row of csv but not header? In Python我有一个带有标题的 CSV 文件。想要删除前 5 行 csv 但不删除标题?在 Python 中
【发布时间】:2017-12-07 09:12:30
【问题描述】:

我有一个带有标题(A、B、C、D)的以下 CSV 文件:

A,B,C,D
1,2,3,4
2,1,3,5
6,8,0,9
4,7,9,2
2,5,4,9
1,1,7,3
2,9,5,6

我想在删除前 5 行而不是标题后输出:

A,B,C,D
1,1,7,3
2,9,5,6

以下是我的 Python 代码 sn-p,但无法添加任何标题保留代码:

使用 open(filename.csv , 'rb') 作为 infile: data_in = infile.readlines()

使用 open ('temp.csv', 'wb') 作为输出文件: outfile.writelines(data_in[5:])

请帮助我。在我的情况下,标题也在删除,但我想每次都保留标题。

【问题讨论】:

  • 简单解决方案:使用两个outfile.writelines() 命令,一个用于data_in[0],然后用于data_in[5:]
  • 谢谢@VBB,成功了

标签: python python-2.7 csv


【解决方案1】:

我建议使用 pandas,因为它会保留标题并且您可以执行 轻松对数据进行多项操作。 pandas 数据框可以以类似于 csv 文件的列和行的形式表示 2D 数据。

将文件加载到 pandas 数据帧中

df = pd.read_csv('file.csv')

然后选择需要的行

df_temp = df.loc[5:]

这里是必需的输出

   A  B  C  D
5  1  1  7  3
6  2  9  5  6

您可以进一步将其写入 csv 文件

df_temp.to_csv('output.csv',index=False)

【讨论】:

    【解决方案2】:

    怎么样:

    with open ('temp.csv', 'wb') as outfile:
        outfile.writelines(data_in[0])
        outfile.writelines(data_in[5:])
    

    【讨论】:

      【解决方案3】:

      您可以使用islice() 来避免将整个文件读入内存:

      from itertools import islice
      import csv
      
      with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
          csv_input = csv.reader(f_input)
          csv_output = csv.writer(f_output)
          csv_output.writerow(next(csv_input))
          csv_output.writerows(islice(csv_input, 5, None))
      

      给你一个输出:

      A,B,C,D
      1,1,7,3
      2,9,5,6
      

      这首先读取第一行并将其写入输出。然后它使用islice()跳过5行,然后将剩余的行传递给writerows()

      【讨论】:

        【解决方案4】:

        我建议反对甚至解析文件或在内存中将其全部读取以对其进行切片。如果你只是想去掉中间的一些行,你只需要逐行读取输入文件并决定将哪些行写入输出文件以及跳过哪些行:

        skip_lines = range(1, 6)  # the range is zero-indexed
        
        with open("input.csv") as f_in, open("output.csv", "w") as f_out:
            current_line = 0  # keep a line counter
            for line in f_in:  # read the input file line by line
                if current_line not in skip_lines:
                    f_out.write(line)  # not in our skip range, write the line
                current_line += 1  # increase the line counter
        

        【讨论】:

          【解决方案5】:

          我建议使用 csv.DictReader 和 csv.DictWriter:

          filename = os.path.join(datapath, "input.csv")
          with open(filename, 'rb') as infile:
              reader = csv.DictReader(infile) 
              data_in = [row for row in reader]
              fieldnames = reader.fieldnames
          
          filename = os.path.join(datapath, "temp.csv")
          with open(filename, 'wb') as outfile: 
              writer = csv.DictWriter(outfile, fieldnames=fieldnames)
              writer.writeheader()
              writer.writerows(data_in[5:])
          

          【讨论】:

            猜你喜欢
            • 2011-06-25
            • 2016-12-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-10-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多