1. Write and generate a csv file
Code:
# Coding: UTF-8
Import csv
Csvfile = file('csv_test.csv ', 'wb ')
Writer = csv. writer (csvfile)
Writer. writerow (['name', 'age', 'phone'])
Data = [
('Shanghai', '25', '123 '),
('Xiaofang ', '18', '123 ')
]
Writer. writerows (data)
Csvfile. close ()
W in wb indicates the write mode, and B indicates the file mode.
Write a row using writerow
Writerows for multiple rows
2. Read csv files
Code:
# Coding: UTF-8
Import csv
Csvfile = file('csv_test.csv ', 'rb ')
Reader = csv. reader (csvfile)
For line in reader:
Print line
Csvfile. close ()
Running result:
Root @ he-desktop :~ /Python/example # python read_csv.py
['\ Xe5 \ xa7 \ x93 \ xe5 \ x90 \ x8d', '\ xe5 \ xb9 \ xb4 \ xe9 \ xbe \ x84 ', '\ xe7 \ x94 \ xb5 \ xe8 \ xaf \ x9d']
['\ Xe5 \ xb0 \ x8f \ xe6 \ xb2 \ xb3', '25', '123']
['\ Xe5 \ xb0 \ x8f \ xe8 \ x8a \ xb3', '18', '123']
Author: lixiang0522