python之讀取和寫入csv文件

寫入csv文件源碼:python

 
 1 #輸出數據寫入CSV文件
 2 import csv
 3 data = [
 4     ("Mike", "male", 24),
 5     ("Lee", "male", 26),
 6     ("Joy", "female", 22)
 7 ]
 8 
 9 #Python3.4之後的新方式,解決空行問題
10 with open('d://write.csv', 'w', newline='') as csv_file:
11     csv_writer = csv.writer(csv_file)
12     for list in data:
13         print(list)
14         csv_writer.writerow(list)
 

讀取csv文件源碼:app

 
 1 #讀取csv文件內容
 2 import csv
 3 list  = []
 4 reader = csv.reader(open("d://demo.csv"))
 5 #csv中有三列數據,遍歷讀取時使用三個變量分別對應
 6 for title, year, director in reader:
 7   list.append(year)
 8   print(title, "; ",  year , "; ",  director)
 9 
10 print(list)
 

 

讀取運行結果:spa

python建立和讀取csv文件 - 星瑞 - 星瑞的博客
 
 
讀取csv文件內容更多方式:
 1 # 讀取csv文件內容
 2 # date:2017-08-26
 3 import csv
 4 
 5 file = "d://write.csv"
 6 
 7 
 8 def csv_read(file):
 9     '''
10     獲取每一個元素
11     :param file: 讀取文件
12     :return: 元素列表
13     '''
14     with open(file) as file:
15         list = []
16         csv_reader = csv.reader(file)
17         for id, data, *args in csv_reader:
18             # 跳過表頭
19             if id == "   ":
20                 continue
21             print(id, data)
22             list.append(data)
23         return list
24 
25 
26 def csv_read_by_next(file):
27     '''
28     逐行取值
29     :param file: 讀取文件
30     :return: 逐行打印內容(列表形式)
31     '''
32     with open(file) as file:
33         csv_reader = csv.reader(file)
34         while True:
35             try:
36                 csv_next_row = next(csv_reader)
37             except:
38                 break
39             else:
40                 print(csv_next_row)
41 
42 
43 csv_read_by_next(file)
44 '''
45 ['Mike', 'male', '24']
46 ['Lee', 'male', '26']
47 ['Joy', 'female', '22']
48 '''
相關文章
相關標籤/搜索