<p>这是最后的代码</p>
<p>不确定这是不是最好的方式,但对我来说已经足够好了</p>
<pre><code>#!/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=csv_headers)
# Write the columns header into the csv file
csv_writer.writeheader()
for key, val in final_data.items():
# ?
row = {'FQDN': key}
# Update the row with all columns values
row.update(val)
# If service contains multiple elements it will transform the list into a string with each string separate by a space
# If service contains just one element, it will transform the list into a string (no space) added
row['service'] = ' '.join(val['service'])
# Write a row for each value in the port list
for port in val['port']:
row['port'] = port
csv_writer.writerow(row)
</code></pre>
<p>结果输出:</p>
<pre><code>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'
</code></pre>
<p>不要投票支持我的答案,我把它作为知识的目的。
所有奖励都应归@bartonstanley所有</p>