2017-02-15 3 views
1

내 데이터는 다음과 같이 구성되어 있습니다. 30 개의 폴더가 있습니다. 각각에 3 개의 하위 폴더가 있습니다. 각각에 하나의 파일.파이썬으로 파일에 목록을 쓰는 방법

이 폴더 1의 하위 폴더에있는 파일의 경로를 폴더 1에있는 텍스트 파일 1에 쓰는 스크립트를 작성하고 싶습니다. 다른 모든 폴더에 대해서도 마찬가지입니다.

문제는 스크립트 만, 각 텍스트 파일에, 제 3 파일 (하위 폴더 3 파일)보다는 하위 1, 2의 파일을, 3

이것은 내가 뭘하려 기록이다 :

import glob 
import os 

gotofolders = '/path/to/folderslocation/' 
foldersname = open('/path/to/foldersname.txt').read().split() 

for folders in foldersname: 
    foldersdirectory = os.path.join(gotofolders,foldersname) 
    filepaths = glob.glob(os.path.join(foldersdirectory)+'*subfolders/*files') 
    for filepath in filepaths: 
     savethepaths = os.path.join(foldersdirectory)+'files_path_in_that_folder.txt' 
     with open (savethepaths,'w') as f: 
      f.write(filepath+'\n') 

마찬가지로 'files_path_in_that_folder.txt'에는 "filepath"목록의 세 번째 요소가 있는데,이 요소는 모두 3 가지 요소가 아닙니다.

감사합니다.

답변

1

좋아요, 알아 냈습니다. 나는 추가했다 :이 작업을해야

with open (savethepaths,'w') as f: 
    f.writelines(list("%s\n" %filepath for filepath in filepaths)) 
1
import os 
def directory_into_file(_path, file_obj, depth): 
# depth is a string of asterisk, just for better printing. starts with empty string 
file_obj.write(depth + _path + '\n') 
if(os.path.isdir(_path)): 
    file_list = os.listdir(_path) 
    os.chdir(_path) 
    for file in file_list: 
     directory_into_file(file, file_obj, depth+'*') 


    os.chdir("..") 

. _path - 디렉토리의 경로 file_obj - 기능과 첫째, 깊이로 오브젝트 파일을 전송 - 첫 번째 호출에서 빈 문자열

이 작동 할 희망을 보낼 수 있습니다. 직접 시도하지 않았습니다 ...

관련 문제