<p>我没有使用csv库,因为你的csv没有报头,并且有可变数量的开放端口。它更简单,代码/深度更少。这种方式。在</p>
<p><strong>没有csv软件包的版本1</strong></p>
<pre><code>import os, sys
from collections import defaultdict
def main(csv):
# use defaultdict so there is no need to initialize
# use set to remove duplicate entries
port_ip_map = defaultdict(set)
# open with, handles errors open closing file handles etc.
with open(csv, 'r') as f:
# read lines
lines = f.readlines()
for line in lines:
# ip must always be the first entry
# port lists can have a variable length
ip, *ports = line.split(',')
for port in ports:
# save ips by port
port = int(port.strip())
port_ip_map[port].add(ip)
for port, ips in port_ip_map.items():
line = ' '.join(ips)
with open('{}.txt'.format(port), 'w') as f:
f.write(line)
if __name__ == '__main__':
# main(sys.argv[1]) # pass csv file by cli
main('./test1.csv')
</code></pre>
<p><strong>带有csv软件包的版本2</strong></p>
^{pr2}$
<p>示例输入:test1.csv</p>
<pre><code>192.168.10.49,22,80,21
192.168.10.45,80,443,20,21,8080
</code></pre>
<p>样本输出:</p>
<pre><code>defaultdict(<class 'set'>, {22: {'192.168.10.49'}, 80: {'192.168.10.45', '192.168.10.49'}, 21: {'192.168.10.45', '192.168.10.49'}, 443: {'192.168.10.45'}, 20: {'192.168.10.45'}, 8080: {'192.168.10.45'}})
</code></pre>