2013-11-22 1 views
0

다른 폴더에있는 txt 파일의 많은 부분에서 요약 파일을 만들어야합니다. 파이썬으로 시작했는데, 제공된 모든 솔루션이 괜찮습니다. 파이썬, AWK, bash는여러 txt 파일의 결과 파일 합치기

내가 하위 폴더에서 요약-파일을 검색하고 결과 파일에 TXT 파일의 결과를 컴파일 할 필요가
find = "find -name \"summary.txt\" > output.txt" 
os.system(find) 

o = open("output.txt", "r") 
read = o.readlines() 
for items in read: 
    pilko = items.split("/") 
    id = pilko[1] 

. 나는 txt 파일을 for 루프에서 열어 데이터를 결과 파일에 저장하고 계속 이동하는 방법에 대해 다소 당황 스럽다. 내가 노력 접근 방식이지만, 모두가 실패

plate = pilko[4] 
print id+"/"+pilko[2]+"/"+pilko[3]+"/"+plate+"/"+pilko[5] 
foo = open("id+"/"+pilko[2]+"/"+pilko[3]+"/"+plate+"/"+pilko[5]", "r") 

:

나는 아직 듣지 못한 것을이 작업을 수행하는 쉬운 방법이 상상할 수있다.

+1

'id'는 내장 된 메소드입니다. 변수로 사용하지 마십시오. – Farhadix

+0

일부 샘플 입력과 예상 출력을 게시하십시오. –

답변

0
for f in `find -name 'summary.txt' -print` ; do cat $f >> /tmp/grandsummary.txt ; done 
+1

더 간단해질 수 있습니다 :'cat $ (find. -name 'summary.txt')> grandsummary.txt'. 인수가 너무 많으면'찾는다. -name 'summary.txt'-print0 | xargs -0 고양이> grandsummary.txt'. 또는 재귀 적으로,'cat **/summary.txt> grandsummary.txt' – xmo

0

코드 색상을 보면 마지막 줄의 인용 부호가 잘못되었습니다. 또한 os.path API를 사용해야합니다. 그리고 with 파일이 올바르게 닫혀 있는지 확인하십시오. 마지막으로, 필요가 없습니다 readline, 파일은 라인의 iterable입니다. 마지막으로 수동으로 경로를 재구성하는 이유는 무엇입니까? 왜 open(items, 'rb')가 아닌가?

0

여기 파이썬 솔루션입니다 :

import os 
with open('/path/to/result/file.txt', 'wb') as result_file: 
    for root, dirs, files in os.walk('/path/to/start/directory'): # walk the file system 
     if 'file_name_I_want.txt' in files: # This folder has the file i'm looking for! 
      with open(os.path.join(root, 'file_name_I_want.txt'), 'rb') as src_file: # open it up 
       result_file.write(src_file.read()) # Read from src, store in dest. 

이 메모리에서 기록 된, 그래서 일부 jiggering이 필요할 수 있습니다.

관련 문제