CSV文件的读取与写入

发布时间 2023-10-19 12:39:44作者: Picassooo

写入CSV文件

save_path = '/home/wp/st_detection/download_code/toy.csv'
with open(save_path, 'w', newline='') as csvfile:
    det_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    det_writer.writerow(['brush_hair/April_09_brush_hair_u_nm_np1_ba_goo_0', 0.1, 0.1, 0.5, 0.5, 0.98])
    det_writer.writerow(['brush_hair/April_09_brush_hair_u_nm_np1_ba_goo_0', 0.2, 0.2, 0.6, 0.6, 0.92])

写入结果:

 

读取CSV文件

path = '/home/wp/st_detection/download_code/toy.csv'
with open(path, newline='') as csvfile:
    det_reader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in det_reader:  # row 是一个列表
        print('   '.join(row))

输出结果:

 

本文参考:csv --- CSV 文件读写 — Python 3.12.0 文档