csV (Comma [ˈkɒmə] Separated [ˈsepəreɪtɪd] Values),即逗号分隔值(也称字符分隔值,因为分隔符可以不是逗号),是一种常用的文本格式,用以存储表格数据,包括数字或者字符。是数据分析中最常用的文件格式之一。
官网链接:https://docs.python.org/3/library/csv.html#module-csv
import csv file = open('csv_test.csv', 'w', newline='', encoding='utf-8') writer = csv.writer(file) # 写入一行用writerow writer.writerow(['姓名', '年龄', '电话']) data = [ ('典韦', '25', '13678909002'), ('张苞', '18', '13678908003') ] # 多行用writerows writer.writerows(data) file.close()
import csv headers = ['name', 'age'] datas = [{'name': '刘备', 'age': 33}, {'name': '关羽', 'age': 31}, {'name': '张飞', 'age': 29} ] with open('csv_test.csv', 'w', newline='', encoding='utf-8') as f: # 标头在这里传入,作为第一行数据 writer = csv.DictWriter(f, headers) writer.writeheader() for row in datas: # 单行方式写入 writer.writerow(row) # 还可以写入多行 writer.writerows(datas)
import csv with open('csv_test.csv', 'r', encoding='utf-8') as file: reader = csv.reader(file) for row in reader: print(row)
import csv with open('csv_test.csv', 'r', encoding='utf-8') as file: reader = csv.DictReader(file) for row in reader: print(row['name'], row['age'])