Skip to content

Commit fa509be

Browse files
author
steven.chen3
committed
csv file read and write
1 parent dca1508 commit fa509be

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

helloworld/read_write_csv_40.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import csv
2+
3+
4+
def read_csv(filename):
5+
file_instance = open(filename, encoding="UTF8")
6+
7+
csv_reader = csv.reader(file_instance)
8+
9+
for line in csv_reader:
10+
print(line)
11+
12+
file_instance.close()
13+
14+
15+
def write_csv(filename):
16+
file_instance = open(filename, "w", encoding="UTF8")
17+
18+
csv_writer = csv.writer(file_instance)
19+
20+
header = ['Name', 'Chinese', 'English', 'Math']
21+
rows = [
22+
['Zhangsan', '80', '87', '100'],
23+
['Lisi', '78', '79', '98'],
24+
['Wangwu', '67', '90', '88']
25+
]
26+
27+
csv_writer.writerow(header)
28+
csv_writer.writerows(rows)
29+
30+
file_instance.close()
31+
32+
33+
def dict_write_csv(filename):
34+
file_instance = open(filename, "w", encoding="UTF8")
35+
36+
header = ['name', 'chinese', 'english', 'math']
37+
38+
csv_writer = csv.DictWriter(file_instance, header)
39+
rows = [
40+
{"name": 'Zhangsan',
41+
"chinese": '80',
42+
"english": '87',
43+
"math": '100'},
44+
{"name": 'Lisi',
45+
"chinese": '76',
46+
"english": '80',
47+
"math": '98'},
48+
{"name": 'Wangwu',
49+
"chinese": '60',
50+
"english": '77',
51+
"math": '90'}
52+
]
53+
54+
csv_writer.writeheader()
55+
csv_writer.writerows(rows)
56+
57+
file_instance.close()
58+
59+
60+
if __name__ == '__main__':
61+
filename = "students3.csv"
62+
63+
# write_csv(filename)
64+
dict_write_csv(filename)
65+
read_csv(filename)

helloworld/students.csv

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Name,Chinese,English,Math
2+
Zhangsan,80,87,100
3+
Lisi,78,79,98
4+
Wangwu,67,90,88

0 commit comments

Comments
 (0)