我有以下文本文件。 dummy.txt
Property,Value
status,ACTIVE
updated,2014-04-26T17:01:27Z
OS-EXT_STS:task-state,None
OS-EXT-ATTR:host,noe-001
key_name,dummy-host
image,1234d46g-354f-89fg-23fg-45fhty56fjd7
mine-internalnetwork,192.168.50.10,10.10.80.40
hostId,123g3124h4h32h3h432h4324h2jh423j4h32k4h32jh432j4hj2k342
Property,Value
status,ACTIVE
updated,2014-04-25T17:01:27Z
OS-EXT_STS:task-state,None
OS-EXT-ATTR:host,noe-002
key_name,dummy-host1
image,1234d46g-fh56-8h5g-23fg-4556fhtmggjg
mine-internalnetwork,192.168.49.10,10.10.80.39
hostId,436bx8fbby747ycb4y7535afggoirif947307ffh8tycfu34yxycf84
现在,我想打印如下所示的结果,其中属性和值后第2列的值发生了变化。
status,updated,OS-EXT_STS:task-state,OS-EXT-ATTR:host,key_name,image,mine-internalnetwork,hostId
ACTIVE,2014-04-26T17:01:27Z,None,noe-001,dummy-host,1234d46g-354f-89fg-23fg-45fhty56fjd7,192.168.50.10,10.10.80.40
ACTIVE,2014-04-25T17:01:27Z,None,noe-002,dummy-host1,1234d46g-fh56-8h5g-23fg-4556fhtmggjg,192.168.49.10,10.10.80.39
这是我的代码: 导入csv 导入子流程 导入系统 import os
from collections import defaultdict
columns = defaultdict(list)
open('dummy.txt.txt')为f: reader = csv.DictReader(f) 读者行: 对于row.items()中的(k,v): 列[K] .append(v)的
打印(列[ '属性']) 打印(列[ '值'])
我得到的输出如下。
./ testdb_update3.py ['status','updated','OS-EXT_STS:task-state','OS-EXT-ATTR:host','key_name','image','mine-internalnetwork','hostId'] ['ACTIVE','2014-04-26T17:01:27Z','无','noe-001','dummy-host','1234d46g-354f-89fg-23fg-45fhty56fjd7','192.168.50.10' ,'123g3124h4h32h3h432h4324h2jh423j4h32k4h32jh432j4hj2k342']
dummy.txt文件:(此文件不包含多个值,我稍后尝试并发布问题)
状态,ACTIVE 更新,2014-04-26T17:01:27Z OS-EXT_STS:任务状态,无 OS-EXT-ATTR:主机,NOE-001 KEY_NAME,虚拟主机 图像,1234d46g-354F-89fg-23fg-45fhty56fjd7 雷internalnetwork,192.168.50.10,10.10.80.40 HOSTID,123g3124h4h32h3h432h4324h2jh423j4h32k4h32jh432j4hj2k342
答案 0 :(得分:3)
对于数据,您应该使用Pandas。试试这个:
import pandas as pd
from pandas import DataFrame as df
import numpy as np
f = open('dummy.txt','r')
text = f.read()
t = np.array([i.split(',')[1] for i in text.split('\n')])
t = t.reshape(len(t)/9,9)
A = df(t[:,1:], columns=['status', 'updated', 'OS-EXT_STS:task-state', 'OS-EXT-ATTR:host', 'key_name',
'image', 'mine-internalnetwork', 'hostId', ])
for p in A.columns.values:
print(p,end=', ')
for i in A.values:
for j in i:
print(j,end=', ')
print('\n',end='')
另外,如果要将信息导入csv(常见任务),请使用以下命令:
A.to_csv('out.csv',index=False)