文章目录
  1. python的100个实例002-读写CSV文件

python的100个实例002-读写CSV文件

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
import csv
# 打开文件
TEST_FILE = "textFiles/csvTestFile.csv"
print("**********第一种方式")
with open(TEST_FILE) as csvFile:
CSV_FILE = csv.reader(csvFile)
for ROW in CSV_FILE:
print(ROW)
print("**********第二种方式")
# 打开csv文件的函数
def open_and_print(file_path):
with open(file_path) as csvFile:
# MAP格式的内容,每一行都可以通过列名读取
dict_csv = csv.DictReader(csvFile)
for row in dict_csv:
for key, value in row.items():
print("%s:%s" % (key,value), end='\t\t\t')
print("")
return
open_and_print(TEST_FILE)
print("**********写入CSV文件")
def save_csv(file_path, header, rows):
with open(file_path, 'w') as f_to_save:
# lineterminator='\n'指定行尾为换行结束,否则默认为两个换行结束
f_csv = csv.writer(f_to_save, lineterminator='\n')
f_csv.writerow(headers)
f_csv.writerows(rows)
return
headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
]
save_csv('textFiles/stocks.csv', headers, rows)
open_and_print('textFiles/stocks.csv')

output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
['AA', '39.48', '6/11/2007', '9:36am', '-0.18', '181800']
['AIG', '71.38', '6/11/2007', '9:36am', '-0.15', '195500']
['AXP', '62.58', '6/11/2007', '9:36am', '-0.46', '935000']
['BA', '98.31', '6/11/2007', '9:36am', '+0.12', '104800']
['C', '53.08', '6/11/2007', '9:36am', '-0.25', '360900']
['CAT', '78.29', '6/11/2007', '9:36am', '-0.23', '225400']
**********第二种方式
Symbol:AA Price:39.48 Date:6/11/2007 Time:9:36am Change:-0.18 Volume:181800
Symbol:AIG Price:71.38 Date:6/11/2007 Time:9:36am Change:-0.15 Volume:195500
Symbol:AXP Price:62.58 Date:6/11/2007 Time:9:36am Change:-0.46 Volume:935000
Symbol:BA Price:98.31 Date:6/11/2007 Time:9:36am Change:+0.12 Volume:104800
Symbol:C Price:53.08 Date:6/11/2007 Time:9:36am Change:-0.25 Volume:360900
Symbol:CAT Price:78.29 Date:6/11/2007 Time:9:36am Change:-0.23 Volume:225400
**********写入CSV文件
Symbol:AA Price:39.48 Date:6/11/2007 Time:9:36am Change:-0.18 Volume:181800
Symbol:AIG Price:71.38 Date:6/11/2007 Time:9:36am Change:-0.15 Volume:195500
Symbol:AXP Price:62.58 Date:6/11/2007 Time:9:36am
文章目录
  1. python的100个实例002-读写CSV文件