python讀取寫入csv文件
csv文件 讀取保存操作
官方文檔:https://docs.Python.org/3/library/csv.html
寫入
# -*- encoding: utf-8 -*- import csv from io import StringIO from urllib import urlopen # 按行元組參數寫入 def writerCsv1(): f = open("data.csv", "w") writer = csv.writer(f) for i in range(100): writer.writerow((i+1, i+2, i+3)) f.close() # 按行字典參數寫入 def writerCsv2(): f = open("data.csv", "w") writer = csv.DictWriter(f, ["name", "age"]) for i in range(100): dct = {"name":i+1, "age": i+2} writer.writerow(dct) f.close() print("寫入成功!") writerCsv2()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
讀取
要讀取的文件
# MontyPythonAlbums.csv Name,Year Monty Python's Flying Circus,1970 Another Monty Python Record,1971 Monty Python's Previous Record,1972
1
2
3
4
5
6
# 按行讀取列表 def readerCsv1(): # 讀取網絡文件 # url = "http://www.pythonscraping.com/files/MontyPythonAlbums.csv" # data = urlopen(url).read() # 讀取本地文件 data = open("MontyPythonAlbums.csv", "r").read().decode('utf-8') print type(data) data_file = StringIO(data) # 字符串轉為io對象 csv_reader = csv.reader(data_file) for row in csv_reader: print(row) """ ['Name', 'Year'] ["Monty Python's Flying Circus", '1970'] """ # readerCsv1() # 按行讀取列表 def readerCsv2(): f = open("MontyPythonAlbums.csv", "r") csv_reader = csv.reader(f) for row in csv_reader: print(row) """ ['Name', 'Year'] ["Monty Python's Flying Circus", '1970'] """ f.close() # readerCsv2() # 按行讀取字典,第一行為key def readerCsv3(): f = open("MontyPythonAlbums.csv", "r") csv_reader = csv.DictReader(f) for row in csv_reader: print(row) # {'Name': "Monty Python's Flying Circus", 'Year': '1970'} f.close() # readerCsv3()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Python
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。