gpt4 book ai didi

python - 如何将非常特殊的列表导出到 excel 或 csv

转载 作者:行者123 更新时间:2023-12-04 20:25:28 24 4
gpt4 key购买 nike

嘿,我有一个看起来像这样的列表:

['192.168.0.1  switch1 ff:ff:ff:ff:ff:ff  657 dynamic port:42','10.60.37.2 switch1 ff:ff:ff:ff:ff:ff  657 dynamic port:41','192.168.0.240  switch1 ff:ff:ff:ff:ff:ff  657 dynamic port:40']

当我导出到excell时,每个 block 都在不同的行中,这很好,但都在同一个collunm上,我想在第1列切换第2列等
                                 excel colunm 1
excel row1: 192.168.0.1 switch1 ff:ff:ff:ff:ff:ff 657 dynamic port:42
excel row2: 10.60.37.2 switch1 ff:ff:ff:ff:ff:ff 657 dynamic port:41
excel row3 :192.168.0.240 switch1 ff:ff:ff:ff:ff:ff 657 dynamic port:40

所以我想要这样
          exlcol1        exlcol2       exl.col3     exl.col4 exl.col5 exl.col6 
exlrow1: 192.168.0.1 switch1 ff:ff:ff:ff:ff:ff 657 dynamic port:42
exlrow2: 10.60.37.2 switch1 ff:ff:ff:ff:ff:ff 657 dynamic port:41
exlrow3 :192.168.0.240 switch1 ff:ff:ff:ff:ff:ff 657 dynamic port:40

我试图将它导出到 csv 但它说 wtr.writerows(row) 必须是一个 byte.object 之类的,然后我尝试将我的列表更改为一个字符串以将其更改为 byte.object 但它说我的 wtr .writerows(row) 应该是可交互的。

这是我用来导出到 csv 的代码
import csv
with open('test.csv', 'wb') as f:
wtr = csv.writer(f, delimiter= ',')
for row in data11parts1:
wtr.writerows(row)

with open('test.csv', 'r') as f:
for line in f:
print (line)

我的偏好是将其导出到 Excel,但我认为这可以帮助您更好地解释我的问题和我拥有的数据类型。
只是告诉你我从这个附加中得到了我的 data11parts1:
for element in data2:
elementstring=''.join(element)
for element in res1:
elementstring5=''.join(element)
if elementstring in elementstring5:
with open(Sw1, 'r') as f3:
for line5 in f3:
if elementstring in line5:
print('managemnet-tool' + ' - ' + Sw1.rsplit('.txt',1)[0] + ' - ' + elementstring5.rsplit('-', 1)[0] + ' - ' + line5.rsplit('\n', 1)[0])
data11.append(elementstring5.rsplit('-',1)[0] + ' ' + Sw1.rsplit('.txt',1)[0] + ' ' + line5.rsplit('\n', 1)[0])
data13.append(str(line5.rsplit('\n', 1)[0]))
exit

最佳答案

它提示是因为您打开文件进行二进制写入。 CSV 编写很容易,将您的内部字符串拆分为列表(在空格处拆分)并编写它们:

data = ['192.168.0.1  switch1 ff:ff:ff:ff:ff:ff  657 dynamic port:42',
'10.60.37.2 switch1 ff:ff:ff:ff:ff:ff 657 dynamic port:41',
'192.168.0.240 switch1 ff:ff:ff:ff:ff:ff 657 dynamic port:40']

# split the strings into their columns
dp = [d.split() for d in data]

import csv
with open("data.txt","w", newline="") as f: # w not wb and supply newline
writer = csv.writer(f)

# write em all
writer.writerows(dp)

with open("data.txt") as f:
print(f.read())

文件内容:
192.168.0.1,switch1,ff:ff:ff:ff:ff:ff,657,dynamic,port:42
10.60.37.2,switch1,ff:ff:ff:ff:ff:ff,657,dynamic,port:41
192.168.0.240,switch1,ff:ff:ff:ff:ff:ff,657,dynamic,port:40


  • str.split()
  • csv.writer()
  • 关于python - 如何将非常特殊的列表导出到 excel 或 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61311485/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com