【发布时间】:2020-06-09 07:38:42
【问题描述】:
我正在尝试将以下数据导入 CSV:
{'test.foo.com': {'domain': 'foo.com','FQDN': 'test.foo.com', 'AS': 'AS1111', 'ressource_type': 'A', \
'nb_ip': '1', 'IP': '1.1.1.1', 'service': ['UNKNOWN'], 'port': '[443, 8443]'}}
这段代码我几乎成功了:
#!/bin/python3
## Import ##
# Offical
import csv
### Main ###
if __name__ == '__main__':
## Variables
csv_headers = ['domain', 'FQDN', 'AS', 'ressource_type', 'nb_ip', 'IP', 'service', 'port']
final_data = {'test.foo.com': {'domain': 'foo.com','FQDN': 'test.foo.com', 'AS': 'AS1111', 'ressource_type': 'A', \
'nb_ip': '1', 'IP': '1.1.1.1', 'service': ['UNKNOWN'], 'port': '[443, 8443]'}}
# Open the csv file in "write mode"
with open(file_name, mode='w') as file:
# Prepare the writer to add a dict into the csv file
csv_writer = csv.DictWriter(file, fieldnames=headers)
# Write the columns header into the csv file
csv_writer.writeheader()
# Write the dict into the file
for key, val in nest_dict.items():
row = {'FQDN': key}
row.update(val)
csv_writer.writerow(row)
结果是:
domain,FQDN,AS,ressource_type,nb_ip,IP,service,port
foo.com,test.foo.com,AS1111,A,1,1.1.1.1,['UNKNOWN'],"[443, 8443]"
但我想:
domain,FQDN,AS,ressource_type,nb_ip,IP,service,port
foo.com,test.foo.com,AS1111,A,1,1.1.1.1,'UNKNOWN','443'
foo.com,test.foo.com,AS1111,A,1,1.1.1.1,'UNKNOWN','8443'
看到区别了吗? 我有一个“服务”列表(这里不需要处理)和一个“端口”列表。 如果“端口”列中有超过 1 个端口,我需要为列表中的每个端口打印一个新行。
我很难做到这一点,因为我没有完全理解这段代码:
# Write the dict into the file
for key, val in nest_dict.items():
row = {'FQDN': key}
row.update(val)
csv_writer.writerow(row)
你能帮我解决这个问题吗?
【问题讨论】:
标签: python csv dictionary import