如何在CSV文件的头部列中写入?

2024-05-29 04:07:14 发布

您现在位置:Python中文网/ 问答频道 /正文

def write_vt(d, filename):
    f = open(filename, 'w')

我应该以write模式打开新文件,然后在header列中写入,然后使用for循环将数据字符串添加到文件中。但我就是不知道怎么做。。。在

原始文件名是votes.csv。在


Tags: 文件csv数据字符串for文件名def模式
2条回答

您可以使用此选项添加标题:

header = "col1,col2,col3"
with open('file.csv','w') as my_csv:
    my_csv.write(header+'\n')

关于用数据填充您的CSV,它将取决于您将用作源的原始数据。在

根据您的数据和您愿意使用的工具,有很多种方法可以做到这一点:

a) 用列表和标题逐行写入CSV

import csv


data_list = [
    ["Russia", "Moscow", "Russian"],
    ["US", "Washington, D.C.", "English"],
    ["Colombia", "Bogotá", "Spanish"]
]
header = ["col1", "col2", "col3"]

def write_csv_from_lists(data, header, filename):
    with open(filename, "w") as csv_file:
        csv_writer = csv.writer(csv_file)
        csv_writer.writerow(header) # write header
        for row in data:
            csv_writer.writerow(row) # write each row

write_csv_from_lists(data_list, header, "file1.csv")

文件1.csv

^{pr2}$

b) 用dicts和header逐行写入CSV

import csv


data_dict = [
    {"col1": "Russia", "col2": "Moscow", "col3": "Russian"},
    {"col1": "US", "col2": "Washington, D.C.", "col3": "English"},
    {"col1": "Colombia", "col2": "Bogotá", "col3": "Spanish"}
]
header = ["col1", "col2", "col3"]

def write_csv_from_dicts(data, header, filename):
    with open(filename, "w") as csv_file:
        dict_writer = csv.DictWriter(csv_file, fieldnames=header)
        dict_writer.writeheader() # write header
        for row in data:
            dict_writer.writerow(row) # write each row

write_csv_from_dicts(data_dict, header, "file2.csv")

文件2.csv

^{pr2}$

c) 用熊猫写CSV

import pandas as pd


data_dict = [
    {"col1": "Russia", "col2": "Moscow", "col3": "Russian"},
    {"col1": "US", "col2": "Washington, D.C.", "col3": "English"},
    {"col1": "Colombia", "col2": "Bogotá", "col3": "Spanish"}
]

def write_csv_pandas(data, filename):

    pd.DataFrame(data).to_csv(filename, index=False)

write_csv_pandas(data_dict, "file3.csv")

文件3.csv

^{pr2}$

相关问题 更多 >

    热门问题