티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Python list directory, subdirectory, and files

Python에서 디렉토리, 서브디렉토리 및 파일 목록 만들기

 문제 내용 

I'm trying to make a script to list all directory, subdirectory, and files in a given directory.
I tried this:

주어진 디렉토리의 모든 디렉토리, 서브디렉토리 및 파일 목록을 나열하는 스크립트를 만들려고 합니다.
다음과 같이 시도해 보았습니다.
import sys, os

root = "/home/patate/directory/"
path = os.path.join(root, "targetdirectory")

for r, d, f in os.walk(path):
    for file in f:
        print(os.path.join(root, file))

 

Unfortunatly it doesn't work properly.
I get all the files, but not their complete paths.

하지만 제대로 작동하지 않습니다. 모든 파일을 얻지만 완전한 경로를 얻을 수 없습니다.

 

For example if the dir struct would be:

예를 들어 dir 구조가 다음과 같으면:
 /home/patate/directory/targetdirectory/123/456/789/file.txt 

 

It would print:

그러면 다음과 같이 인쇄됩니다.
 /home/patate/directory/targetdirectory/file.txt 

 

What I need is the first result. Any help would be greatly appreciated! Thanks.

첫 번째 결과가 필요합니다. 도움을 주시면 감사하겠습니다! 감사합니다.

 

 

 

 높은 점수를 받은 Solution 

Use os.path.join to concatenate the directory and file name:

os.path.join을 사용하여 디렉토리와 파일 이름을 연결하세요.
for path, subdirs, files in os.walk(root):
    for name in files:
        print(os.path.join(path, name))

 

Note the usage of path and not root in the concatenation, since using root would be incorrect.

경로를 사용하고 루트를 사용하지 않으며 연결하는 것에 유의하세요. 루트를 사용하면 잘못된 결과가 됩니다.

 


In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join would be:

Python 3.4에서는 경로 조작을 더 쉽게하기 위해 pathlib 모듈이 추가되었습니다. 따라서 os.path.join에 해당하는 것은 다음과 같습니다.
pathlib.PurePath(path, name)

 

The advantage of pathlib is that you can use a variety of useful methods on paths. If you use the concrete Path variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.

pathlib의 장점은 경로에 대해 유용한 다양한 메서드를 사용할 수 있다는 것입니다. 구체적인 경로(Path variant)를 사용하면 실제 OS 호출(디렉토리 변경, 경로 삭제, 가리키는 파일 열기 등)도 할 수 있습니다.

 

 

 

 가장 최근 달린 Solution 

Another option would be using the glob module from the standard lib:

표준 라이브러리의 glob 모듈을 사용하는 다른 옵션은 다음과 같습니다.
import glob

path = "/home/patate/directory/targetdirectory/**"

for path in glob.glob(path, recursive=True):
    print(path)

 

If you need an iterator you can use iglob as an alternative:

이터레이터가 필요하면 대안으로 iglob를 사용할 수 있습니다.
for file in glob.iglob(my_path, recursive=True):
    # ...

 

 

출처 : https://stackoverflow.com/questions/2909975/python-list-directory-subdirectory-and-files

반응형
댓글
공지사항
최근에 올라온 글