Python:附加/合并多个csv文件,并写入csv

Python:附加/合并多个csv文件,并写入csv,python,csv,python-3.x,Python,Csv,Python 3.x,[使用Python3]我对(Python)编程非常陌生,但我正在编写一个脚本,扫描文件夹中的特定csv文件,然后我想全部读取并附加它们,然后将它们写入另一个csv文件 在这两者之间,要求仅当特定列中的值与一组条件匹配时才返回数据 所有csv文件都有相同的列,看起来如下所示: header1 header2 header3 header4 ... string float string float ... string float string float ... stri

[使用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   ...
...     ...     ...     ...     ...
我现在使用的代码如下(如下所示),但它只是不断覆盖上一个文件中的数据。这对我来说很有意义,但我就是不知道如何让它工作

代码:

我还尝试了类似于
readers=list(itertools.chain(*map(lambda f:csv.DictReader(open(f)),files)))
的方法,并尝试迭代读卡器,但是我无法理解如何使用标题。(我得到的错误是itertools.chain()没有fieldnames属性)


非常感谢您的帮助

您一直在重新打开文件并覆盖它

在循环开始之前打开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)

嘿,丹,谢谢你的回答!它就像一个符咒:)仍然试图弄清楚你到底在做什么,以及为什么这真的有效。例如,为什么在打开输出文件后设置
dict\u writer=None
?另外,如果不是dict\u writer:那么为什么需要流语句
?再次感谢!在Python中,如果变量被设置为None,那么它的计算结果将为False。因此,
if not dict\u writer
if dict\u writer note
相同。基本上,这可以确保只创建一次dict_writer。哦,而且
dict_writer=None
不需要在打开文件后执行,也可以在打开文件之前执行。重要的是它发生在循环之外。为了更好地理解Python,我建议您通过Hey Dan进行操作,谢谢您的回复和提示。事实上,我正在通过Diveinto Python3。希望这将是富有成果的。
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)