我是python的新手。任何人都可以告诉我如何使用通用Id映射.yaml文件和.txt文件。
settings.yaml
folders:
input: /home/developer/xovis/alhokair_data/incoming
csv: /home/developer/alhokair_xovis/client_31_csv
backup: /home/developer/xovis/alhokair_data/backup
client_id: 31
logging:
log_file: /tmp/j2clog_31.log
sensors:
-
serial_number: "D8:80:39:D3:C6:3C"
storecode: 105943
chain_id: 1
chain_name: Al Hokair
site_id: 1
site_name: Aldo
zone_id: 2
zone_name: Entrance - 2
Stores.txt
STORE,TRAN_DATE,TRAN_TIME,SALE_AMOUNT,TRAN_COUNT
105943,20170719,090000,88.00,1
105943,20170719,100000,1060.00,6
105943,20170719,120000,498.00,2
使用来自YAML的Storecode和来自.txt文件的商店
映射此2文件最终输出就像
STORE,TRAN_DATE,TRAN_TIME,SALE_AMOUNT,TRAN_COUNT,chain_id,chain_name,site_id,site_name,zone_id,zone_name
105943,20170719,090000,88.00,1,1,1,1,1,2,2
105943,20170719,100000,1060.00,6,1,1,1,1,2,2
105943,20170719,120000,498.00,2,1,1,1,1,2,2
答案 0 :(得分:0)
解析涉及yaml的设置文件很容易。
>>> import yaml
>>> with open('settings.yaml') as settings_file:
... settings = yaml.load(settings_file)
...
>>> settings.keys()
dict_keys(['folders', 'logging', 'client_id', 'sensors'])
在这种情况下,您会收到一本字典,而您对sensors
感兴趣。这是一个清单;选择第一项。
>>> settings['sensors'][0]
{'zone_id': 2, 'serial_number': 'D8:80:39:D3:C6:3C', 'zone_name': 'Entrance - 2', 'site_id': 1, 'chain_name': 'Al Hokair', 'chain_id': 1, 'storecode': 105943, 'site_name': 'Aldo'}
从字典中定义所需项目的名称,然后选择这些项目。
>>> new_items = ['chain_id', 'chain_name','site_id','site_name','zone_id','zone_name']
>>> new_values = ','.join([str(settings['sensors'][0][_]) for _ in new_items])
现在旋转输入文件,将名称添加到第一行,将值添加到第二行和后续行。
>>> with open('stores.txt') as stores:
... line = stores.readline().strip()
... print (line+','+''.join(new_items))
... while True:
... line = stores.readline().strip()
... if not line:
... break
... print (line+','+new_values)
...
STORE,TRAN_DATE,TRAN_TIME,SALE_AMOUNT,TRAN_COUNT,chain_idchain_namesite_idsite_namezone_idzone_name
105943,20170719,090000,88.00,1,1,Al Hokair,1,Aldo,2,Entrance - 2
105943,20170719,100000,1060.00,6,1,Al Hokair,1,Aldo,2,Entrance - 2
105943,20170719,120000,498.00,2,1,Al Hokair,1,Aldo,2,Entrance - 2
请注意,输出并不是您在问题中声明的内容。