programing

디렉터리에 있는 모든 파일 목록?

stoneblock 2023. 10. 26. 20:36

디렉터리에 있는 모든 파일 목록?

를 사용하여 특정 디렉토리 아래에 있는 모든 파일의 목록을 만드는 기능을 만드는 것을 도와줄 수 있는 사람이 있습니까?pathlib도서관?

여기, 나는 다음과 같은 것이 있습니다.

enter image description here

있습니다

  • c:\desktop\test\A\A.txt

  • c:\desktop\test\B\B_1\B.txt

  • c:\desktop\test\123.txt

위의 경로를 포함하는 단일 목록을 가질 것으로 기대했지만 코드는 중첩된 목록을 반환합니다.

여기 내 코드가 있습니다.

from pathlib import Path

def searching_all_files(directory: Path):   
    file_list = [] # A list for storing files existing in directories

    for x in directory.iterdir():
        if x.is_file():

           file_list.append(x)
        else:

           file_list.append(searching_all_files(directory/x))

    return file_list


p = Path('C:\\Users\\akrio\\Desktop\\Test')

print(searching_all_files(p))

누가 나를 바로잡아 줬으면 좋겠어요.

모든 파일 및 디렉토리를 나열합니다.그런 다음 List Comprehensions에서 필터링합니다.

p = Path(r'C:\Users\akrio\Desktop\Test').glob('**/*')
files = [x for x in p if x.is_file()]

더 많은 정보pathlib모듈:

pathlib의 경우 아래 명령과 같이 간단합니다.

path = Path('C:\\Users\\akrio\\Desktop\\Test')    
list(path.iterdir())
from pathlib import Path
from pprint import pprint

def searching_all_files(directory):
    dirpath = Path(directory)
    assert dirpath.is_dir()
    file_list = []
    for x in dirpath.iterdir():
        if x.is_file():
            file_list.append(x)
        elif x.is_dir():
            file_list.extend(searching_all_files(x))
    return file_list

pprint(searching_all_files('.'))

파일 개체만이 다음과 같은 기능을 가진다고 가정할 수 있는 경우.이름(즉, .txt, .png 등)으로 전역 또는 재귀 전역 검색을 수행할 수 있습니다...

from pathlib import Path

# Search the directory
list(Path('testDir').glob('*.*'))

# Search directories and subdirectories, recursively
list(Path('testDir').rglob('*.*'))

하지만 항상 그렇지는 않습니다.때때로 숨겨진 디렉토리가 있습니다..ipynb_checkpoints확장명이 없는 파일도 있습니다.이 경우 목록 이해나 필터를 사용하여 파일인 경로 개체를 정렬합니다.

# Search Single Directory
list(filter(lambda x: x.is_file(), Path('testDir').iterdir()))

# Search Directories Recursively
list(filter(lambda x: x.is_file(), Path('testDir').rglob('*')))
# Search Single Directory
[x for x in Path('testDir').iterdir() if x.is_file()]

# Search Directories Recursively
[x for x in Path('testDir').rglob('*') if x.is_file()]

@prasastoadi's의 것과 유사하고 기능 중심적인 솔루션은 Python의 내장 기능을 사용하여 달성할 수 있습니다.

from pathlib import Path

my_path = Path(r'C:\Users\akrio\Desktop\Test')
list(filter(Path.is_file, my_path.glob('**/*')))

파일의 접미사가 같다면, 예를 들어 다음과 같습니다..txt, 사용가능rglob메인 디렉토리와 모든 하위 디렉토리를 재귀적으로 나열합니다.

paths = list(Path(INPUT_PATH).rglob('*.txt'))

각 경로에 유용한 경로 함수를 적용해야 하는 경우.예를 들어, 에 액세스하는 경우name속성:

[k.name for k in Path(INPUT_PATH).rglob('*.txt')]

어디에INPUT_PATH는 당신의 메인디렉토리로 가는 경로이고,Path가져옴pathlib.

디렉토리 경로 정의:

from pathlib import Path
data_path = Path.home() / 'Desktop/My-Folder/'

모든 경로(파일 및 디렉터리) 가져오기:

paths = sorted(data_path.iterdir())

파일 경로만 가져옵니다.

files = sorted(f for f in Path(data_path).iterdir() if f.is_file())

특정 패턴(예: .png 확장명 사용)을 가진 경로 가져오기:

png_files = sorted(data_path.glob('*.png'))

pathlib2를 사용하는 것이 훨씬 쉽습니다.

from pathlib2 import Path

path = Path("/test/test/")
for x in path.iterdir():
    print (x)
def searching_all_files(directory: Path):   
    file_list = [] # A list for storing files existing in directories

    for x in directory.iterdir():
        if x.is_file():
            file_list.append(x)#here should be appended
        else:
            file_list.extend(searching_all_files(directory/x))# need to be extended

    return file_list
import pathlib

def get_all_files(dir_path_to_search):
    filename_list = []

    file_iterator = dir_path_to_search.iterdir()

    for entry in file_iterator:
            if entry.is_file():
                #print(entry.name)
                filename_list.append(entry.name)

    return filename_list

우리가 테스트할 수 있는 기능은 -

dir_path_to_search= pathlib.Path("C:\\Users\\akrio\\Desktop\\Test")
print(get_all_files(dir_path_to_search))

온라인 필터링과 함께 이와 같은 발전기를 사용할 수 있습니다.

for file in (_ for _ in directory.iterdir() if _.is_file()):
    ...

다음을 사용할 수 있습니다.

folder: Path = Path('/path/to/the/folder/')

files: list = [file.name for file in folder.iterdir()]

os.listdir()를 사용할 수 있습니다.파일과 디렉토리 등 디렉토리에 있는 모든 것을 얻을 수 있습니다.

파일만 원하는 경우 os.path를 사용하여 필터링할 수 있습니다.

from os import listdir
from os.path import isfile, join
onlyfiles = [files for files in listdir(mypath) if isfile(join(mypath, files))]

또는 os.walk ()를 사용하면 방문하는 각 디렉토리에 대해 두 개의 목록이 생성됩니다. 파일과 디렉토리로 분할됩니다.최상위 디렉터리만 원한다면 처음에 생성될 때 바로 중단할 수 있습니다.

from os import walk
files = []
for (dirpath, dirnames, filenames) in walk(mypath):
    files.extend(filenames)
    break

언급URL : https://stackoverflow.com/questions/39909655/listing-of-all-files-in-directory