下面提供一個工具類,關於把數據對象寫入CSV和從CSV 讀取出python
class CSVUtil(object): @staticmethod def save_object_list(file_name, data_list): with open(file_name, "wb") as f: csv_writer = csv.writer(f) if not data_list: return for i, way in enumerate(data_list): assert isinstance(way, WayData) way_dict = way.__dict__ if not i: csv_writer.writerow(way_dict.keys()) csv_writer.writerow(way_dict.values()) print "save data list to %s done." % file_name @staticmethod def read_object_list_dict(file_name): assert os.path.exists(file_name) with open(file_name, "r") as csv_file: csv_reader = csv.DictReader(csv_file) data_dict_list = [d for d in csv_reader] return data_dict_list
python2.7寫入 CSV時,寫模式修改wb,不然會出現多餘的空行。python2.7
讀取的方法,返回對象的字典結構,關於字典結構 向對象的轉換需另行搜索。工具