我想保存一个csv文件:
从…
SWA hostname IP MAC
SWA0 app1,app2,app3,app4,…etc ip1,ip2,ip3,ip4,,,,etc mac1,mac2,mac3,mac4,…etc
SWA1 app12,app13,app14,..etc ip12,ip13,ip14..etc mac12,mac13,mac14,…etc
SWA2 app18,app19,app20,..etc ip18,ip19,ip20..etc mac18,mac19,mac20,…etc至
hostname IP MAC SWA
app1 ip1 mac1 SW0
app2 ip2 mac2 SW0
app3 ip3 mac3 SW0
app4 ip4 mac4 SW0
app11 ip11 mac11 SW1
app12 ip12 mac12 SW1
app13 ip13 mac13 SW1
app14 ip14 mac14 SW1
app18 ip18 mac18 SW2
app19 ip19 mac19 SW2
app20 ip20 mac20 SW2通过在另一个csv文件中搜索,我确实生成了这个csv文件:
def search(csv_file,word):
return [i for i in open(csv_file,'r') if i.find(word) != -1]和
if s:
resu = search('result/result.csv',search_word)
str(resu)
#print(resu)
lenght = len(resu)
filenam = 'result/result_' + str(datetime.datetime.now()) + '.csv'
with open(filenam,'w') as export:
writer = csv.writer(export,delimiter=";")
writer.writerow(headerList)
for line in resu:
line = line.replace('[','').replace(']','').replace("'",'')
export.write('{}'.format(line))我想要的结果和上面显示的不一样。
谢谢。
得到一个分词的答案:
import pandas as pd
df = pd.read_csv('/path/to/sample.csv')
df_reorder = df[['A', 'B', 'C', 'D', 'E']] # rearrange column here
df_reorder.to_csv('/path/to/sample_reorder.csv', index=False)现在的结果是:
hostname ip mac SWA
app1,app2,app3 ip1,ip2,ip3 mac1,mac2,mac3 SW0
app4,app5,app6 ip4,ip5,ip6 mac4,mac5,mac6 SW1
app7,app8,app9 ip7,ip8,ip9 mac7,mac8,mac9 SW2我要把他们派到每一条线路上
发布于 2022-07-06 20:58:47
我不知道Pandas,但我知道Python的CSV模块:
import csv首先,创建output_rows,在创建新的“子行”时存储它们:
output_rows = []您将读取输入CSV并捕获标题:
f_in = open("input.csv", newline="")
reader = csv.reader(f_in)
header = next(reader)然后迭代输入行:
for row in reader:
...每一行都将如下所示:
["swa0", "app1,app2,app3", "ip1,ip2,ip3", "mac1,mac2,mac3"]您需要能够展开列值,然后对展开的值进行分组:每个列的所有第一个项,然后是每个列中的所有第二个项,等等。
你想让那一行看起来像这样:
[
["app1","ip1","mac1"],
["app2","ip2","mac2"],
["app3","ip3","mac3"]
]这样做的方法是拆分每个列,然后使用Python的zip()函数来交织条目:
hostnames = row[1].split(",")
ips = row[2].split(",")
macs = row[3].split(",")
sub_rows = zip(hostnames, ips, macs)sub_rows现在看起来就像上面所示的字符串列表。
现在,为每个子行添加SWA以创建一个新的输出行:
swa = row[0]
for sub_row in sub_rows:
output_row = [swa] + list(sub_row) # sub_row is technically a tuple, so make it a list to append it
output_rows.append(output_row)最后,将输出行写入新的CSV:
f_out = open("output.csv", "w", newline="")
writer = csv.writer(f_out)
writer.writerow(header)
writer.writerows(output_rows)当我把所有这些放在一起并在这个input.csv上运行它时:
SWA,hostname,IP,MAC
SWA0,"app1,app2,app3,app4","ip1,ip2,ip3,ip4","mac1,mac2,mac3,app4"
SWA1,"app12,app13,app14","ip12,ip13,ip14","mac12,mac13,mac14"
SWA2,"app18,app19,app20","ip18,ip19,ip20","mac18,mac19,mac20"我得到了这个output.csv:
SWA,hostname,IP,MAC
SWA0,app1,ip1,mac1
SWA0,app2,ip2,mac2
SWA0,app3,ip3,mac3
SWA0,app4,ip4,app4
SWA1,app12,ip12,mac12
SWA1,app13,ip13,mac13
SWA1,app14,ip14,mac14
SWA2,app18,ip18,mac18
SWA2,app19,ip19,mac19
SWA2,app20,ip20,mac20如果您想在Pandas中这样做,请看一下Pandas解决这个类似问题的一些解决方案:如何根据python中的分隔符将Python中的一行拆分为两行。
https://stackoverflow.com/questions/72869159
复制相似问题