forked from stevencn76/python_tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_write_csv_40.py
More file actions
65 lines (45 loc) · 1.33 KB
/
read_write_csv_40.py
File metadata and controls
65 lines (45 loc) · 1.33 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import csv
def read_csv(filename):
file_instance = open(filename, encoding="UTF8")
csv_reader = csv.reader(file_instance)
for line in csv_reader:
print(line)
file_instance.close()
def write_csv(filename):
file_instance = open(filename, "w", encoding="UTF8")
csv_writer = csv.writer(file_instance)
header = ['Name', 'Chinese', 'English', 'Math']
rows = [
['Zhangsan', '80', '87', '100'],
['Lisi', '78', '79', '98'],
['Wangwu', '67', '90', '88']
]
csv_writer.writerow(header)
csv_writer.writerows(rows)
file_instance.close()
def dict_write_csv(filename):
file_instance = open(filename, "w", encoding="UTF8")
header = ['name', 'chinese', 'english', 'math']
csv_writer = csv.DictWriter(file_instance, header)
rows = [
{"name": 'Zhangsan',
"chinese": '80',
"english": '87',
"math": '100'},
{"name": 'Lisi',
"chinese": '76',
"english": '80',
"math": '98'},
{"name": 'Wangwu',
"chinese": '60',
"english": '77',
"math": '90'}
]
csv_writer.writeheader()
csv_writer.writerows(rows)
file_instance.close()
if __name__ == '__main__':
filename = "students3.csv"
# write_csv(filename)
dict_write_csv(filename)
read_csv(filename)