2017-12-26 50 views
0

파이썬을 사용하여 다른 TXT 파일의 내용을 병합하려고하지만 도전 과제는 다른 폴더에서 오는 동일한 파일 이름의 내용 만 병합해야한다는 것입니다. 지금까지같은 이름이지만 파이썬별로 다른 폴더에있는 파일의 내용을 병합하는 방법은 무엇입니까?

enter image description here, 나는 자신의 모든 경로에있는 모든 파일 이름을 인쇄 할 수 있습니다 : 그러나

import os 

for root, dirs, files in os.walk(".", topdown=False): 
    for file in files: 
     if file.endswith(".txt"): 
      filepath = os.path.join(root, file) 
      print (filepath) 

, 난 단지 파일을 병합에 파이썬을 사용할 수있는 방법을 여기 참조에 대한 스크린 샷입니다 같은 이름으로 ... 아직도 연구 중입니다. 대답을 알고 있다면 알려주거나 더 많은 것을 연구하는 방법을 알려주십시오. 대단히 감사합니다. 즐거운 휴일!

+1

당신이 사용할 수있는''디렉토리는/*/a.txt' – user1767754

+0

같은 이름의 순서는 무엇을 병합하는 것 /와 같은 와일드 카드 glob'? 디렉토리 이름 순서로? –

+0

문제가 무엇인지 언급하지 않았고 해당 파일을 찾거나 병합 했습니까? – user1767754

답변

-1

다음과 같은 조치를 취해야합니다. 코드 테스트를 거치지 마십시오.

import os 

mapped_files = {} 

for path, subdirs, files in os.walk("."): 
    for file in files: 
     if file.endswith(".txt"): 
      if file in mapped_files: 
       existing = mapped_files[file] 
       mapped_files[file] = existing.append(path) 
      else: 
       mapped_files[file] = [path] 

for key in mapped_files: 
    files = mapped_files[key] 
    first_f = os.path.join(path, files[0]) 
    with open(first_f, "a+") as current_file: 
     for path in files[1:]: # start at the second index 
      f = os.path.join(path, key) 
      content = open(f,"r").read() 
      current_file.write(content) # add all content to the first file 
0
import os 

# create a dictionary with file names as keys 
# and for each file name the paths where they 
# were found 
file_paths = {} 
for root, dirs, files in os.walk('.'): 
    for f in files: 
     if f.endswith('.txt'): 
      if f not in file_paths: 
       file_paths[f] = [] 
      file_paths[f].append(root) 

# for each file in the dictionary, concatenate 
# the content of the files in each directory 
# and write the merged content into a file 
# with the same name at the top directory 
for f, paths in file_paths.items(): 
    txt = [] 
    for p in paths: 
     with open(os.path.join(p, f)) as f2: 
      txt.append(f2.read()) 
    with open(f, 'w') as f3: 
     f3.write(''.join(txt))