如何在python中写入csv?

时间:2018-08-22 18:01:21

标签: python file csv

我有一行:

row = {'A':'valueA', 'B':'valueB', 'C':'valueC'}

基本上,我想打开一个新的csv文件,并将每个值写入其列中,例如

 ---------------------------
|   A     |  B     |   C    |
 ---------------------------
|  ValueA | ValueB | ValueC |
 ---------------------------

我正在这样做:

def OandWtonew(filename, row):
with open('Ouput1.csv', 'wt') as csvfile:
    fileout = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    fileout.writerow(row)

但是我得到的输出是:

 --------------------------------------------
|   A           |  B           |  C          |
 --------------------------------------------
|  'A':'valueA' | 'B':'valueB' | 'C':'valueC'|
 --------------------------------------------

非常感谢所有回复:)

3 个答案:

答案 0 :(得分:0)

row的类型为dict。来自documentation

import csv
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

答案 1 :(得分:0)

您可以使用pandas.DataFrame.to_csv()轻松地写入csv:

import pandas as pd

row = {'A':'valueA', 'B':'valueB', 'C':'valueC'}

#Convert dictionary to a pandas dataframe
df = pd.DataFrame().append(row, ignore_index=True)

# check output
df
    A       B       C
0   valueA  valueB  valueC

# Save to a csv file
df.to_csv('Ouput1.csv',index=False)

答案 2 :(得分:0)

由于数据是字典,csv.DictWriter()可能是最简单的方法。 只要确保标头值列表按原始顺序排列,在这种情况下,sorted()可能是最简单的:

with open('Ouput1.csv', 'wt') as csvfile:
    fieldnames = sorted(row.keys())  # needs to be the first line in correct order
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow(row)             # writes corresponding value for key in header

CSV view in Excel