4_4 csv 파일 쓰기

7117 단어
 1 """ csv """
 2 
 3 
 4 import csv
 5 
 6 #
 7 def write_csv_demo1():
 8     headers = ['username', 'age', 'height']
 9     values = [
10         (' ', 18, 180),
11         (' ', 19, 190),
12         (' ', 20, 120)
13     ]
14     with open('csvwriter1.csv', 'w', encoding='gbk', newline='') as fp:
15         fp.writer = csv.writer(fp)
16         fp.writer.writerow(headers)
17         fp.writer.writerows(values)
18 
19 #
20 def write_csv_demo2():
21     headers = ['username', 'age', 'height']
22     values = [
23         {'username': ' ', 'age': 18, 'height': 180},
24         {'username': ' ', 'age': 19, 'height': 190},
25         {'username': ' ', 'age': 20, 'height': 120}
26     ]
27     with open('csvwriter2.csv', 'w', encoding='utf-8', newline='') as fp:
28         write = csv.DictWriter(fp, headers)
29         write.writeheader() #  
30         write.writerows(values)
31 
32 if __name__ == "__main__":
33     write_csv_demo1()
34     write_csv_demo2()

좋은 웹페이지 즐겨찾기