1.读取csv文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# encoding=utf-8 import csv with open('ad_info.csv', 'r') as f: csv_file = csv.reader(f) ''' 读取的csv_file是一个iterator,每个元素代表一行 ''' for i in csv_file: print(i) ''' ['5223', 'CPC', '6', '3', '2', '73'] ['5222', 'CPC', '6', '3', '2', '73'] ['5221', 'CPC', '234', '3', '2', '73'] ['5220', 'CPC', '234', '8', '2', '73'] ['5219', 'CPC', '234', '3', '2', '73'] ''' |
2.写入csv文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# encoding=utf-8 import csv with open('student.csv', 'w') as f: # 如果在windows下打开csv出现空行的情况,加一个newline=''参数 stu = [ ['xyu', 22], ['xpt', 20] ] head = ['name', 'age'] csv_writer = csv.writer(f) csv_writer.writerow(head) # 写一行 csv_writer.writerows(stu) # 写多行 |