Python将数据写入CSV文件:先写标题,再写数据

一:列表模式

import csv

# 定义数据
data = [
    ['John', 'Doe', 28],
    ['Jane', 'Doe', 26],
    ['Bob', 'Smith', 32]
]

# 打开文件并写入数据
with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['First Name', 'Last Name', 'Age'])
    writer.writerows(data)

print('数据已写入CSV文件')

二:字典模式

    with open(store_file, 'w', encoding='utf-8', newline='') as f:
        fieldnames = ['A', 'B', 'C', 'D']  # 表头
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        every_dict = { }  # 字典格式的要写入的数据,keys为表头,word为数据
        writer.writerow(every_dict)

import csv
 
list_a = ['张三','李四','王五']
list_b = ['23','36','31']
list_c = ['大学','大专','初中']
list_d = ['2020','2022','2015']
 
data_list = []
for a,b,c,d in zip(list_a,list_b,list_c,list_d):
    x = {}
    x['姓名']= a
    x['年龄']= b
    x['学历'] = c
    x['入职时间'] = d
    data_list.append(x)
#print(data_list)
 
with open("多列表写入csv.csv",'w',newline='',encoding='UTF-8') as f_c_csv:
    writer = csv.writer(f_c_csv)
    writer.writerow(['姓名', '年龄','学历','入职时间'])
    for nl in data_list:
        writer.writerow(nl.values())
print("写入完成!")

注意:默认newline参数的值为\n,在writerow输出一行换行后,还会再次换行,就会导致两条数据之间存在空行的问题,将newline设置为空就可以解决这个文件

你可能感兴趣的:(python,python,1024程序员节)