【问题标题】:Create subset of large CSV file and write to new CSV file创建大型 CSV 文件的子集并写入新的 CSV 文件
【发布时间】:2016-08-11 01:56:54
【问题描述】:

我想使用第 4 列为“DOT”的行创建大型 CSV 文件的子集并输出到新文件。

这是我目前拥有的代码:

import csv
outfile = open('DOT.csv','w')
with open('Service_Requests_2015_-_Present.csv', newline='', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        if row[3] == "DOT":
            outfile.write(row)
outfile.close()

错误是:

  outfile.write(row)
TypeError: must be str, not list

如何操作行,以便我能够直接执行 write(row),如果没有,最简单的方法是什么?

【问题讨论】:

    标签: python csv


    【解决方案1】:

    在上面的代码中,您尝试使用文件对象编写列表,我们无法编写给出错误“TypeError:必须是 str,而不是列表”的列表,您可以将列表转换为字符串格式,然后您就可以在文件中写入行。 outfile.write(str(row))

    import csv
    def csv_writer(input_path,out_path):
        with open(out_path, 'ab') as outfile:
            writer = csv.writer(outfile)
            with open(input_path, newline='', encoding='utf-8') as f:
                reader = csv.reader(f)
                for row in reader:
                    if row[3] == "DOT":
                        writer.writerow(row)
            outfile.close()
    

    csv_writer(input_path,out_path) [此代码适用于 Python 3 版本。在 Python 2.7 中,open 函数不接受换行参数,因此会出现 TypeError。]

    【讨论】:

      【解决方案2】:

      您可以组合两个开放语句,因为 with 语句接受多个参数,如下所示:

      import csv
      
      infile = 'Service_Requests_2015_-_Present.csv'
      outfile = 'DOT.csv'
      
      with open(infile, encoding='utf-8') as f, open(outfile, 'w') as o:
          reader = csv.reader(f)
          writer = csv.writer(o, delimiter=',') # adjust as necessary
          for row in reader:
             if row[3] == "DOT":
                 writer.writerow(row)
      
      # no need for close statements
      print('Done')
      

      【讨论】:

      • 现在我收到此错误:UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 119: ordinal not in range(128)
      【解决方案3】:

      将您的outfile 设为csv.writer 并使用writerow 而不是写。

      outcsv = csv.writer(outfile, ...other_options...)
      ...
      outcsv.writerow(row)
      

      我就是这样做的……或者

      outfile.write(",".join(row)) # comma delimited here...
      

      【讨论】:

      • 你还得写换行符。
      猜你喜欢
      • 1970-01-01
      • 2018-08-01
      • 2023-02-24
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多