program story

재귀 하위 폴더 검색 및 목록 파이썬에서 파일 반환

inputbox 2020. 9. 13. 10:31
반응형

재귀 하위 폴더 검색 및 목록 파이썬에서 파일 반환


메인 폴더의 하위 폴더를 재귀 적으로 살펴보고 특정 파일 형식으로 목록을 작성하는 스크립트를 작성 중입니다. 스크립트에 문제가 있습니다. 현재 다음과 같이 설정됩니다.

for root, subFolder, files in os.walk(PATH):
    for item in files:
        if item.endswith(".txt") :
            fileNamePath = str(os.path.join(root,subFolder,item))

문제는 subFolder 변수가 ITEM 파일이있는 폴더가 아닌 하위 폴더 목록을 가져 오는 것입니다. 나는 이전에 하위 폴더에 대해 for 루프를 실행하고 경로의 첫 번째 부분에 가입하려고 생각했지만 Id는 그 전에 제안 사항이 있는지 확인하기 위해 다시 확인했습니다. 당신의 도움을 주셔서 감사합니다!


당신은 dirpath당신이 부르는을 사용해야합니다 root. dirnames당신이 원하는하지 않는 폴더가있는 경우 당신이 그것을 치다 수 공급 os.walk에 재귀하는가.

import os
result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(PATH) for f in filenames if os.path.splitext(f)[1] == '.txt']

편집하다:

최근에 반대표를 던진 후 glob확장으로 선택하는 것이 더 나은 도구 라는 생각 들었습니다 .

import os
from glob import glob
result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.txt'))]

또한 생성기 버전

from itertools import chain
result = (chain.from_iterable(glob(os.path.join(x[0], '*.txt')) for x in os.walk('.')))

Python 3.4 이상용 Edit2

from pathlib import Path
result = list(Path(".").rglob("*.[tT][xX][tT]"))

Python 3.5 에서 변경 : "**"를 사용하는 재귀 glob 지원.

glob.glob()새로운 재귀 매개 변수를 얻었습니다 .

모든 .txt파일을 아래 로 가져 오려면 my_path(재귀 적으로 하위 디렉토리 포함) :

import glob

files = glob.glob(my_path + '/**/*.txt', recursive=True)

# my_path/     the dir
# **/       every file and dir under my_path
# *.txt     every file that ends with '.txt'

반복기가 필요하면 iglob 을 대안으로 사용할 수 있습니다 .

for file in glob.iglob(my_path, recursive=False):
    # ...

다른 사람이 이해하는 데 문제가있을 경우를 대비하여 John La Rooy의 목록 이해 를 중첩 대상으로 번역 하겠습니다.

result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.txt'))]

다음과 동일해야합니다.

import glob

result = []

for x in os.walk(PATH):
    for y in glob.glob(os.path.join(x[0], '*.txt')):
        result.append(y)

다음은 목록 이해력os.walkglob.glob 함수에 대한 문서입니다 .


가장 비단뱀적인 대답은 아니지만 재귀에 대한 깔끔한 교훈이기 때문에 재미로 여기에 넣을 것입니다.

def find_files( files, dirs=[], extensions=[]):
    new_dirs = []
    for d in dirs:
        try:
            new_dirs += [ os.path.join(d, f) for f in os.listdir(d) ]
        except OSError:
            if os.path.splitext(d)[1] in extensions:
                files.append(d)

    if new_dirs:
        find_files(files, new_dirs, extensions )
    else:
        return

내 컴퓨터에는 두 개의 폴더가 root있으며root2

mender@multivax ]ls -R root root2
root:
temp1 temp2

root/temp1:
temp1.1 temp1.2

root/temp1/temp1.1:
f1.mid

root/temp1/temp1.2:
f.mi  f.mid

root/temp2:
tmp.mid

root2:
dummie.txt temp3

root2/temp3:
song.mid

이 디렉토리 중 하나에서 .txt모든 .mid파일 을 찾고 싶다고 가정 해 봅시다.

files = []
find_files( files, dirs=['root','root2'], extensions=['.mid','.txt'] )
print(files)

#['root2/dummie.txt',
# 'root/temp2/tmp.mid',
# 'root2/temp3/song.mid',
# 'root/temp1/temp1.1/f1.mid',
# 'root/temp1/temp1.2/f.mid']

새로운 pathlib라이브러리는 이것을 한 줄로 단순화합니다.

from pathlib import Path
result = list(Path(PATH).glob('**/*.txt'))

생성기 버전을 사용할 수도 있습니다.

from pathlib import Path
for file in Path(PATH).glob('**/*.txt'):
    pass

이것은 Path당신이 거의 모든 것에 사용할 수있는 객체를 반환 하거나 file.name.


Recursive is new in Python 3.5, so it won't work on Python 2.7. Here is the example that uses r strings so you just need to provide the path as is on either Win, Lin, ...

import glob

mypath=r"C:\Users\dj\Desktop\nba"

files = glob.glob(mypath + r'\**\*.py', recursive=True)
# print(files) # as list
for f in files:
    print(f) # nice looking single line per file

Note: It will list all files, no matter how deep it should go.


This function will recursively put only files into a list. Hope this will you.

import os


def ls_files(dir):
    files = list()
    for item in os.listdir(dir):
        abspath = os.path.join(dir, item)
        try:
            if os.path.isdir(abspath):
                files = files + ls_files(abspath)
            else:
                files.append(abspath)
        except FileNotFoundError as err:
            print('invalid directory\n', 'Error: ', err)
    return files

참고URL : https://stackoverflow.com/questions/18394147/recursive-sub-folder-search-and-return-files-in-a-list-python

반응형