python2 csv写入和读取
下面提供一个工具类,关于把数据对象写入CSV和从CSV 读取出
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,否则会出现多余的空行。
读取的方法,返回对象的字典结构,关于字典结构 向对象的转换需另行搜索。