티스토리 뷰

반응형

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

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

 

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

Directory-tree listing in Python

Python의 디렉터리 트리 목록

 문제 내용 

How do I get a list of all files (and directories) in a given directory in Python?

파이썬에서 주어진 디렉토리에 있는 모든 파일(및 디렉터리)의 목록을 가져오려면 어떻게 해야 합니까?

 

 

 

 높은 점수를 받은 Solution 

This is a way to traverse every file and directory in a directory tree:

디렉토리 트리의 모든 파일 및 디렉터리를 이동하는 방법은 다음과 같습니다.
import os

for dirname, dirnames, filenames in os.walk('.'):
    # print path to all subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    # print path to all filenames.
    for filename in filenames:
        print(os.path.join(dirname, filename))

    # Advanced usage:
    # editing the 'dirnames' list will stop os.walk() from recursing into there.
    if '.git' in dirnames:
        # don't go into any .git directories.
        dirnames.remove('.git')

 

 

 가장 최근 달린 Solution 

While os.listdir() is fine for generating a list of file and dir names, frequently you want to do more once you have those names - and in Python3, pathlib makes those other chores simple. Let's take a look and see if you like it as much as I do.

os.listdir()은 파일 및 dir 이름 목록을 생성하는 데 적합하지만 해당 이름이 있으면 더 많은 작업을 수행하려는 경우가 많습니다. Python3에서는 pathlib가 다른 작업을 간단하게 만듭니다. 한 번 살펴보고 저만큼 마음에 드는지 봅시다.

 

To list dir contents, construct a Path object and grab the iterator:

dir 콘텐츠를 나열하려면 Path 개체를 구성하고 iterator를 가져옵니다.
In [16]: Path('/etc').iterdir()
Out[16]: <generator object Path.iterdir at 0x110853fc0>

 

If we want just a list of names of things:

이름 리스트만 원하는 경우:
In [17]: [x.name for x in Path('/etc').iterdir()]
Out[17]:
['emond.d',
 'ntp-restrict.conf',
 'periodic',

 

If you want just the dirs:

만약 당신이 단지 dirs를 원한다면:
In [18]: [x.name for x in Path('/etc').iterdir() if x.is_dir()]
Out[18]:
['emond.d',
 'periodic',
 'mach_init.d',

 

If you want the names of all conf files in that tree:

트리에 있는 모든 conf 파일의 이름을 원하는 경우:
In [20]: [x.name for x in Path('/etc').glob('**/*.conf')]
Out[20]:
['ntp-restrict.conf',
 'dnsextd.conf',
 'syslog.conf',

 

If you want a list of conf files in the tree >= 1K:

트리 >= 1K에서 conf 파일 목록을 원하는 경우:
In [23]: [x.name for x in Path('/etc').glob('**/*.conf') if x.stat().st_size > 1024]
Out[23]:
['dnsextd.conf',
 'pf.conf',
 'autofs.conf',

 

Resolving relative paths become easy:

상대 경로를 쉽게 확인할 수 있습니다.
In [32]: Path('../Operational Metrics.md').resolve()
Out[32]: PosixPath('/Users/starver/code/xxxx/Operational Metrics.md')

 

Navigating with a Path is pretty clear (although unexpected):

경로를 사용한 탐색은 매우 명확합니다(예상치 못했지만).
In [10]: p = Path('.')

In [11]: core = p / 'web' / 'core'

In [13]: [x for x in core.iterdir() if x.is_file()]
Out[13]:
[PosixPath('web/core/metrics.py'),
 PosixPath('web/core/services.py'),
 PosixPath('web/core/querysets.py'),

 

 

출처 : https://stackoverflow.com/questions/120656/directory-tree-listing-in-python

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