我有一个名为ipValues.csv的csv文件,其中包含以下数据:
IPs Values
192.168.1.231 c3s8b1p1 c3s8b1p2 c3s4b1p3
192.168.1.179 c1s1b1p1 c1s1b1p2 c1s3b1p1 c3s2b1p2 c3s2b1p3
192.168.1.195 c1s1b2p8
192.168.1.162 c1s4b7p8 c1s1b1p3 c1s1b2p2 c1s1b2p3 c1s1b2p5
192.168.1.179 c1s1b1p1 c1s1b1p2 c1s3b1p1 c3s2b1p2 c3s2b1p3
192.168.1.143 c2s4b1p2 c2s2b1p3 c2s2b1p5 c2s2b1p9
192.168.1.231 c3s8b1p1 c3s8b1p2 c3s4b1p3 c3s7b1p6 c2s2b1p1
192.168.1.187 c5s4b1p2 c4s9b1p3
192.168.1.114 c1s1b1p10 c1s3b6p1 c1s1b10p9 c4s10b1p1
192.168.1.132 c1s1b2p1 c1s10b7p8 c4s9b1p1 c4s9b1p2 c3s6b1p3
192.168.1.164 c1s1b1p5 c1s1b1p9 c1s1b1p8 c1s1b2p2 c3s5b1p2
我想以下列格式创建另一个csv文件:
values Ips
c3s8b1p1 192.168.1.231
c3s8b1p2 192.168.1.231
c3s4b1p3 192.168.1.231
c1s1b1p1 192.168.1.179
c1s1b1p2 192.168.1.179
c1s3b1p1 192.168.1.179
c3s2b1p2 192.168.1.179
c3s2b1p3 192.168.1.179
依旧......
我知道这些人很难理解,但我不知道如何解释这一点,对不起。请给我一些建议。
答案 0 :(得分:1)
以下内容应该帮助您开始并帮助解释如何在小文件上使用:
import csv
with open('ipValues.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)
next(csv_input) # skip header
csv_output.writerow(["values", "Ips"])
for row in csv_input:
for entry in row[1:]:
csv_output.writerow([entry, row[0]])
为您提供CSV输出文件,如下所示:
values,Ips
c3s8b1p1,192.168.1.231
c3s8b1p2,192.168.1.231
c3s4b1p3,192.168.1.231
c1s1b1p1,192.168.1.179
c1s1b1p2,192.168.1.179
c1s3b1p1,192.168.1.179
c3s2b1p2,192.168.1.179
c3s2b1p3,192.168.1.179
c1s1b2p8,192.168.1.195
c1s4b7p8,192.168.1.162
c1s1b1p3,192.168.1.162
c1s1b2p2,192.168.1.162
c1s1b2p3,192.168.1.162
c1s1b2p5,192.168.1.162
c1s1b1p1,192.168.1.179
c1s1b1p2,192.168.1.179
c1s3b1p1,192.168.1.179
c3s2b1p2,192.168.1.179
c3s2b1p3,192.168.1.179
c2s4b1p2,192.168.1.143
c2s2b1p3,192.168.1.143
c2s2b1p5,192.168.1.143
c2s2b1p9,192.168.1.143
c3s8b1p1,192.168.1.231
c3s8b1p2,192.168.1.231
c3s4b1p3,192.168.1.231
c3s7b1p6,192.168.1.231
c2s2b1p1,192.168.1.231
c5s4b1p2,192.168.1.187
c4s9b1p3,192.168.1.187
c1s1b1p10,192.168.1.114
c1s3b6p1,192.168.1.114
c1s1b10p9,192.168.1.114
c4s10b1p1,192.168.1.114
c1s1b2p1,192.168.1.132
c1s10b7p8,192.168.1.132
c4s9b1p1,192.168.1.132
c4s9b1p2,192.168.1.132
c3s6b1p3,192.168.1.132
c1s1b1p5,192.168.1.164
c1s1b1p9,192.168.1.164
c1s1b1p8,192.168.1.164
c1s1b2p2,192.168.1.164
c3s5b1p2,192.168.1.164
这是使用Python 2.7测试的。它使用Python的csv
库来解析和创建文件中的CSV条目。