1. Read
Read the content in the file above and print:
1 import csv 2 3 4 rows = csv.reader(open('22.csv', 'r')) 5 for row in rows: 6 print(row)
The print result is as follows:
2. Write (list data)
. 1 Import CSV 2 . 3 . 4 # to be written content . 5 head = [ ' Name ' , ' aged ' , ' city ' , ' Remarks ' ] . 6 rows = [ . 7 [ ' Bob ' , 8 ' Beijing ' ], 8 [ ' red ' , 7, ' Tianjin ' ] 9 ] 10 . 11 # written 12 with open('22.csv', 'w',newline='') as f: 13 f_csv_writer = csv.writer(f) 14 f_csv_writer.writerow(head) 15 f_csv_writer.writerows(rows)
The write result is as follows:
3. Write (dictionary data)
1 import csv 2 3 4 headers = ['class', 'name', 'sex', 'height', 'year'] 5 rows = [ 6 {'class':1, 'name':'xiaoming', 'sex':'male', 'height':168, 'year':23}, 7 {'class':1, 'name':'erha', 'sex':'female', 'height':166, 'year':22} 8 ] 9 with open('22.csv', 'w',newline='') as f: f_csv =10 csv.DictWriter(f, headers) 11 f_csv.writeheader() 12 f_csv.writerows(rows)
The write result is as follows: