用于处理csv或管道分隔数据等平面文件的可变记录类型
vinyl的Python项目详细描述
用于处理平面文件(如CSV或管道分隔数据)的可变记录类型。
处理扁平文件很痛苦。相反,使用乙烯基来声明性地描述和验证 通用平面文件格式。乙烯基为您提供方便的属性样式访问 类似于namedtuple,但使用适合轻松转换数据的可变数据类型。
importosimportcsvfromvinyl.recordimportRecordfromvinyl.fieldsimportVarCharField,FixedCharField# declare the data formatclassTestRecord(Record):customer_name=VarCharField(max_length=50)customer_number=FixedCharField(field_length=10,pad_with='0',justify='right')start_time=FixedCharField(value='00:00:00',field_length=8)# create an instancerecord=TestRecord()# read data from a filewithopen(os.path.join(os.path.dirname(__file__),'example.txt'))asf:reader=csv.reader(f)# copy a row of CSV data to the recordinstancerecord._load(*reader.next())# check the name was read correctlyassertrecord.customer_name=='a customer name with max length=50'# set a different customer numberrecord.customer_number='3'# number is reformatted according to the field settingsassertrecord.customer_number=='0000000003'# a static fieldassertrecord.start_time=='00:00:00'printrepr(record)# >>> TestRecord(customer_name=u'a customer name with max length=50',# customer_number=u'0000000003', start_time=u'00:00:00')