创建大型CSV文件的子集并写入新的CSV文件

时间:2016-04-19 05:08:54

标签: python csv

我想使用第4列ass" DOT"并输出到新文件。

这是我目前的代码:

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

如何操作行以便我能够直接写入(行),如果不是,那么最简单的方法是什么?

3 个答案:

答案 0 :(得分:0)

outfile成为csv.writer并使用writerow代替写作。

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

我就是这样做的......或者

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

答案 1 :(得分:0)

您可以组合两个开放语句,因为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')

答案 2 :(得分:0)

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

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。]