2011-12-29 2 views
0

저는 서버 트리를 .txt 파일에서 가져 와서 파이썬 사전에 쓰고 데이터베이스에서 읽을 수 있도록 CSV 파일에 추가 작성하는 작업을하고있었습니다. 내가 fx에서 열면. 엑셀, 나는 그것이 헤더와 함께 나열되기를 바랍니다.헤더를 사용하여 csv에 파이썬 사전을 하나만 만들려면 어떻게해야합니까?

EDIT : 모든 길이의 로그 파일을로드하고 모든 것을 얻을 수있는 방식으로 일반화해야합니다. 완료되었습니다.

사전을 csv 파일에 기록하는 부분에 갇혀 있습니다. 내 다음 스크립트는 다음과 같으며 분리 된 주석 처리 된 파일은 내가 작성하는 데 사용한 시도입니다. csv로

#<><><><><><><><><><><><><><><><><><><><><><><># 
#str = 'lement1, lement2' 
#arr = ['lement1, lement2'] 

#import csv 
#f = open('sometest2.csv', 'wb') 
#wtr = csv.DictWriter(f, dictionary.viewkeys()) 
#for element in dictionary.viewitems(): 
# print element 
# for e in element: 
#  print e 
#wtr.writerow(0) 
#f.close() 
#wtr.writerows(allTimes) 
#wtr.writerows(allTypes) 
#wtr.writerows(allWhos) 
#wtr.writerows(allIds) 
#wtr.writerows(allMsgs) 
#print dictionary 

#<><><><><><><><><><><><><><><><><><><><><><><># 

import csv 
f = open('sometest2.csv', 'wb') 
wtr = csv.DictWriter(f, dictionary.viewkeys()) 
for row in dictionary: f.write("%s%s" %(delimiter.join([row[name] for name in fieldnames]),lineterminator)) 
+0

나는 이것을 썼다. http://code.activestate.com/recipes/577996-ordered-csv-read-write-with-colum-based-lookup/?in=user-4177968 정확하게 그것이 필요한지 모르겠다. 그러나 조작이 쉽고 컬럼 기반 인덱싱이 가능합니다. – pyInTheSky

답변

4

문제에 쓸 수

lineArray = [] 
    timeArray = [] 
    typeArray = [] 
    whoArray = [] 
    idArray = [] 
    msgArray = [] 

    infile = open('C:\SomeArea\data.txt', 'r') 
    dictionary = {'time','type','who','id','msg'} 
    for line in infile: 
     timeInString = line[:24] 
     timeInStringStripped = timeInString.strip() 
     timeArray.append(timeInStringStripped) 
     allTimes = ', '.join(timeArray) 

#The last 4 fields was removed here to take less space 

    infile.close() 
    dictionary = {'time': allTimes, 'type': allTypes, 'who': allWhos, 'id': allIds, 'msg': allMsgs} 

절반 시도 코드 목록의 사전을 쓰려고 할 csv.DictWriter이 사전의 목록을 기대하고 있다는 것입니다.

csv 모듈을 사용하여 데이터를 구문 분석하는 올바른 방법은 각 행을 사전으로 저장하는 것입니다. 따라서 대신에 이런 일이있는의 :

data = [] 
for line in infile: 
    row = {} 
    row['time'] = ... 
    row['type'] = ... 
    ... 
    ... 
    data.append(row) 

과 :

data = [{'time': time_row_1, 
     'type': type_row_1, 
     'who': who_row_1, 
     'id': id_row_1, 
     'msg': msg_row_1}, 

     ... 

     {'time': time_row_n, 
     'type': type_row_n, 
     'who': who_row_n, 
     'id': id_row_n, 
     'msg': msg_row_n}, 
     ] 

따라서, 파일에서 읽을 수있는 코드가 같아야합니다

dictionary = {'time': allTimes, 
       'type': allTypes, 
       'who': allWhos, 
       'id': allIds, 
       'msg': allMsgs} 

당신이 뭔가를해야한다 파일에 쓰는 코드는 다음과 같습니다.

wtr = csv.DictWriter(open(filename, 'w'), keys) 
wtr.writerows(data) 
+0

allTimes, alln은 자동으로 다른 길이의 로그를 처리합니다. time_row_1, _row_2 등으로 자동화 된 것을 볼 수 없으므로 csv.DictWriter로 자동화 된 프로세스를 만드는 방법이 있습니까? –

관련 문제