Python-100-Days/Day01-15/code/Day11/csv2.py

45 lines
837 B
Python
Raw Normal View History

2018-04-27 00:00:22 +08:00
"""
写入CSV文件
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import csv
class Teacher(object):
2019-05-03 21:17:36 +08:00
def __init__(self, name, age, title):
self.__name = name
self.__age = age
self.__title = title
self.__index = -1
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
@property
def name(self):
return self.__name
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
@property
def age(self):
return self.__age
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
@property
def title(self):
return self.__title
2018-04-27 00:00:22 +08:00
filename = 'teacher.csv'
teachers = [Teacher('骆昊', 38, '叫兽'), Teacher('狄仁杰', 25, '砖家')]
try:
2019-05-03 21:17:36 +08:00
with open(filename, 'w') as f:
writer = csv.writer(f)
for teacher in teachers:
writer.writerow([teacher.name, teacher.age, teacher.title])
2018-04-27 00:00:22 +08:00
except BaseException as e:
2019-05-03 21:17:36 +08:00
print('无法写入文件:', filename)
2018-04-27 00:00:22 +08:00
else:
2019-05-03 21:17:36 +08:00
print('保存数据完成!')