Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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_Python 3.x_Python 2.7 - Fatal编程技术网

Python 将打印输出写入csv文件

Python 将打印输出写入csv文件,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我需要帮助在编写代码打印输出到csv文件。代码发布在下面。谢谢你的帮助 import csv result = {} with open('data.csv', 'rb') as csvfile: csvreader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in csvreader: if row[0] in result: result[row[0]].a

我需要帮助在编写代码打印输出到csv文件。代码发布在下面。谢谢你的帮助

import csv

result = {}

with open('data.csv', 'rb') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',', quotechar='"')
    for row in csvreader:
        if row[0] in result:
            result[row[0]].append(row[1])
        else:
            result[row[0]] = [row[1]]

print result

使用
csv.writer
result
中的行写入输出流:

with open('output.csv', 'w') as csvfile:
    csvwriter = csv.writer(csvfile)
    for row in result.items():
        csvwriter.writerow(row)

您可能不想以这种方式使用
print
,您只想使用
csv
库的
writer
方法。如果这是您自己的
读取器
代码,那么您对实现
编写器
有足够的了解。检查一下你想实现什么以及你已经尝试了什么?提供示例输入和所需输出。我是python新手,我使用其他帖子中的示例代码复制了我的场景,并按照建议编辑了我的答案。谢谢。@krishnaoadba很高兴能帮上忙。如果你认为这个答案是正确的,你能把它标记为接受吗?当然,我很乐意这样做,我在屏幕上的任何地方都看不到接受按钮,我该怎么做?请advice@krishnaoadba谢谢只需单击答案旁边的灰色复选标记。请参阅