1

[使用 Python3] 我对(Python)编程非常陌生,但仍在编写一个脚本来扫描文件夹中的某些 csv 文件,然后我想将它们全部读取并附加它们并将它们写入另一个 csv 文件。

在这两者之间,要求仅在某些列中的值与设置的条件匹配时才返回数据。

所有 csv 文件都有相同的列,并且看起来像这样:

header1 header2 header3 header4 ...
string  float   string  float   ...
string  float   string  float   ...
string  float   string  float   ...
string  float   string  float   ...
...     ...     ...     ...     ...

我现在正在使用的代码如下(如下),但它只是继续覆盖前一个文件中的数据。这对我来说确实有意义,但我只是不知道如何让它工作。

代码:

import csv
import datetime
import sys
import glob
import itertools
from collections import defaultdict

# Raw data files have the format like '2013-06-04'. To be able to use this script during the whole of 2013, the glob is set to search for the pattern '2013-*.csv'
files = [f for f in glob.glob('2013-*.csv')]

# Output file looks like '20130620-filtered.csv'
outfile = '{:%Y%m%d}-filtered.csv'.format(datetime.datetime.now())

# List of 'Header4' values to be filtered for writing output
header4 = ['string1', 'string2', 'string3', 'string4']

for f in files:
    with open(f, 'r') as f_in:
        dict_reader = csv.DictReader(f_in)

        with open(outfile, 'w') as f_out:
            dict_writer = csv.DictWriter(f_out, lineterminator='\n', fieldnames=dict_reader.fieldnames)
            dict_writer.writeheader()
            for row in dict_reader:
                if row['Campaign'] in campaign_names:
                    dict_writer.writerow(row)

我也尝试过类似readers = list(itertools.chain(*map(lambda f: csv.DictReader(open(f)), files))), 并尝试遍历读者,但是我无法弄清楚如何使用标题。(我得到 itertools.chain() 没有 fieldnames 属性的错误)。

很感谢任何形式的帮助!

4

1 回答 1

3

您不断重新打开文件并覆盖它。

在循环开始之前打开 outfile 一次。对于您读取的第一个文件,写入标题和行。对于其余文件,只需写入行。

就像是

with open(outfile, 'w') as f_out:
    dict_writer = None
    for f in files:
        with open(f, 'r') as f_in:
            dict_reader = csv.DictReader(f_in)
            if not dict_writer:
                dict_writer = csv.DictWriter(f_out, lineterminator='\n', fieldnames=dict_reader.fieldnames)
                dict_writer.writeheader()
            for row in dict_reader:
                if row['Campaign'] in campaign_names:
                    dict_writer.writerow(row)
于 2013-06-19T13:20:01.487 回答