2014-03-07 3 views
1

누군가 올바른 방향으로 나를 가리킬 수 있다고 생각하지 않습니까?파이썬이 파일을 여러 목록으로 읽음

텍스트 파일에서 값을 가져 와서이를 깨뜨리고 해당 값과 같은 위치의 목록에 다시 넣는 것이 가장 이상 할 지 궁금합니다.

죄송합니다. 명확하지 않으면 어쩌면 명확 해집니다. 이 파일을 출력하는 코드입니다

#while loop  
with open('values', 'a') as o: 
      o.write("{}, {}, {}, {}, {}, {}, {}\n".format(FirstName[currentRow],Surname[currentRow], AnotherValue[currentRow], numberA, numberB)) 
currentRow+1 

내가 반대를하고 위의 형식의 값을 받아 같은 장소에서 목록으로 다시 넣어 싶습니다. 뭔가 같은 :

#while loop 
with open('values', 'r') as o: 
      o.read("{}, {}, {}, {}, {}, {}, {}\n".format(FirstName[currentRow],Surname[currentRow], AnotherValue[currentRow], numberA, numberB)) 
currentRow +1 

감사

+0

내가 높은 ['cvs'] (http://docs.python.org/2/library/csv.html) 모듈에보고 추천 할 것입니다. 이렇게하면 행을 함께 수동으로 꿰맬 필요없이 쓸 수 있으며 각 행에서 다시 읽으면 목록이됩니다. – thegrinner

답변

0

나는 그것이 읽을 텍스트에 split 호출 할 수있는 최선의 대응 방법을 생각 :처럼,

FirstName[currentRow],Surname[currentRow], AnotherValue[currentRow], numberA, numberB = o.read().strip().split(", ") 

이 서식 입력의 실제 동등한 없습니다를 scanf in C.

0

다음과 같이 할 수 있습니다.

first_names = [] 
surnames = [] 
another_values = [] 
number_as = [] 
number_bs = [] 

for line in open('values', 'r'): 
    fn, sn, av, na, nb = line.strip().split(',') 
    first_names.append(fn) 
    surnames.append(sn) 
    another_values.append(av) 
    number_as.append(float(na)) 
    number_bs.append(float(nb)) 

파일의 각 라인과 fn, sn, av, na, nb = line.strip().split(',') 비트 위에 for line in open() 부분 반복은 각 라인의 끝에 떨어져 줄 바꿈 \n 스트립와 쉼표에 분할합니다.

실제로는 CSV Module 또는 Pandas과 같은 것을 사용하지만 가장자리의 경우를 더 잘 처리합니다. 예를 들어 위의 접근법은 이름이나 다른 값에 쉼표가 있으면 중단됩니다!

0
with open('values.txt', 'r') as f: 
    first_names, last_names, another_values, a_values, b_values = \ 
    (list(tt) for tt in zip(*[l.rstrip().split(',') for l in f])) 

업데이트가 필요하지 않으면 목록 변환 list(tt) for tt in도 필요하지 않습니다.

zip 대신 izip에서 itertools을 사용할 수 있습니다.

0

파일 형식을 결정할 수 있으면 json 형식으로 저장하고로드하는 것이 유용 할 수 있습니다.

import json 

#test data 
FirstName = range(5) 
Surname  = range(5,11) 
AnotherValue = range(11,16) 
numberAvec = range(16,21) 
numberBvec = range(21,26) 

#save 
all = [FirstName,Surname,AnotherValue,numberAvec,numberBvec] 
with open("values.txt","w") as fp: 
    json.dump(all,fp) 

#load 
with open("values.txt","r") as fp: 
    FirstName,Surname,AnotherValue,numberAvec,numberBvec = json.load(fp) 

values.txt :

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]] 
관련 문제