Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将新字典值添加到现有csv_Python_Csv - Fatal编程技术网

Python 将新字典值添加到现有csv

Python 将新字典值添加到现有csv,python,csv,Python,Csv,我正在尝试向同一程序中的现有文件添加2个新列。csv由上一个函数生成 在这里查看了许多答案后,我尝试了这个方法,但它不起作用,因为我无法使用csv dict writer在其中找到任何答案,它们都是关于csv writer。这将创建一个包含这两列的新文件。我能得到一些帮助吗 for me, sp in zip(meds, specs): print(me.text, sp.text) dict2 = {"Medicines": me.text, "S

我正在尝试向同一程序中的现有文件添加2个新列。csv由上一个函数生成

在这里查看了许多答案后,我尝试了这个方法,但它不起作用,因为我无法使用
csv dict writer
在其中找到任何答案,它们都是关于
csv writer
。这将创建一个包含这两列的新文件。我能得到一些帮助吗

for me, sp in zip(meds, specs):
    print(me.text, sp.text)
    dict2 = {"Medicines": me.text, "Specialities": sp.text}
    with open(f'Infusion_t{zip_add}.csv', 'r') as read, \
            open(f'(Infusion_final{zip_add}.csv', 'a+', encoding='utf-8-sig', newline='') as f:
        reader = csv.reader(read)
        w = csv.DictWriter(f, dict2.keys())
        for row in reader:
            if not header_added:
                w.writeheader()
                header_added = True
            row.append(w.writerow(dict2))

您需要将新列附加到
,然后将
写入输出文件。您不需要字典或
DictWriter

您还可以在循环之前只打开一次输出文件,并在那里写入头文件,而不是每次都通过主循环

with open(f'(Infusion_final{zip_add}.csv', 'w', encoding='utf-8-sig', newline='') as f:
    w = csv.writer(f)
    w.writerow(['col1', 'col2', 'col3', ..., 'Medicines', 'Specalities']) # replace colX with the names of the original columns
    for me, sp in zip(meds, specs):
        print(me.text, sp.text)
        with open(f'Infusion_t{zip_add}.csv', 'r') as read:                
            reader = csv.reader(read)
            for row in reader:
                row.append(me.text)
                row.append(sp.text)
                w.writerow(row)

嵌套循环将在列表和CSV文件之间创建一个叉积,这是您想要的吗?或者它们应该是1对1的对应关系?对于上一个文件行中的1个值,它们应该为同一索引添加多行,但在2个不同的列中。我没有说到那一部分,因为到现在为止它还没有写出来。就像前面的文件有一个歌手的名字。这是他的歌曲和专辑。类似的。你是对的,它重复标题。我应该只打开一次。非常感谢,我已经尝试了一个小时。您添加的
header\u
变量应该可以防止重复header。但这种方法更简单。