문제

Python의 주어진 디렉토리에서 모든 파일 (및 디렉토리) 목록을 어떻게 얻습니까?

도움이 되었습니까?

해결책

이것은 디렉토리 트리에서 모든 파일과 디렉토리를 가로 지르는 방법입니다.

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')

다른 팁

당신이 사용할 수있는

os.listdir(path)

참조 및 더 많은 OS 기능을 위해 여기를 살펴 봅니다.

다음은 자주 사용하는 도우미 기능입니다.

import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]
import os

for filename in os.listdir("C:\\temp"):
    print  filename

글로브 능력이 필요한 경우 모듈도 있습니다. 예를 들어:

import glob
glob.glob('./[0-9].*')

다음과 같은 것을 반환합니다.

['./1.gif', './2.txt']

문서를 참조하십시오 여기.

이 시도:

import os
for top, dirs, files in os.walk('./'):
    for nm in files:       
        print os.path.join(top, nm)

경로를 지정하지 않고 현재 작업 디렉토리의 파일의 경우

파이썬 2.7 :

import os
os.listdir(os.getcwd())

Python 3.x :

import os
os.listdir()

Python 3.x에 대한 의견을 보내신 Stam Kaly에게 감사드립니다

재귀 구현

import os

def scan_dir(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir, name)
        if os.path.isfile(path):
            print path
        else:
            scan_dir(path)

나는 필요한 모든 옵션과 함께 긴 버전을 썼습니다. http://sam.nipl.net/code/python/find.py

여기에도 적합 할 것 같아요 :

#!/usr/bin/env python

import os
import sys

def ls(dir, hidden=False, relative=True):
    nodes = []
    for nm in os.listdir(dir):
        if not hidden and nm.startswith('.'):
            continue
        if not relative:
            nm = os.path.join(dir, nm)
        nodes.append(nm)
    nodes.sort()
    return nodes

def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):
    root = os.path.join(root, '')  # add slash if not there
    for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
        if relative:
            parent = parent[len(root):]
        if dirs and parent:
            yield os.path.join(parent, '')
        if not hidden:
            lfiles   = [nm for nm in lfiles if not nm.startswith('.')]
            ldirs[:] = [nm for nm in ldirs  if not nm.startswith('.')]  # in place
        if files:
            lfiles.sort()
            for nm in lfiles:
                nm = os.path.join(parent, nm)
                yield nm

def test(root):
    print "* directory listing, with hidden files:"
    print ls(root, hidden=True)
    print
    print "* recursive listing, with dirs, but no hidden files:"
    for f in find(root, dirs=True):
        print f
    print

if __name__ == "__main__":
    test(*sys.argv[1:])

파일 만 재귀 적으로 나열하는 멋진 하나의 라이너입니다. 나는 이것을 내 setup.py package_data directive에서 사용했습니다.

import os

[os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]]

나는 그것이 질문에 대한 답이 아니라는 것을 알고 있지만, 유용 할 수 있습니다.

파이썬 2의 경우

#!/bin/python2

import os

def scan_dir(path):
    print map(os.path.abspath, os.listdir(pwd))

파이썬 3

필터 및 맵의 경우 list ()로 래핑해야합니다.

#!/bin/python3

import os

def scan_dir(path):
    print(list(map(os.path.abspath, os.listdir(pwd))))

이제 권장 사항은 맵 및 필터 사용을 발전기 표현식 또는 목록 이해로 바꾸는 것입니다.

#!/bin/python

import os

def scan_dir(path):
    print([os.path.abspath(f) for f in os.listdir(path)])

다음은 한 줄 Pythonic 버전입니다.

import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]

이 코드는 주어진 디렉토리 이름에 모든 파일 및 디렉토리의 전체 경로를 나열합니다.

다음은 또 다른 옵션입니다.

os.scandir(path='.')

PATH에 의해 주어진 디렉토리의 항목 (파일 속성 정보와 함께)에 해당하는 os.DIRENTRY 객체의 반복자를 반환합니다.

예시:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.'):
            print(entry.name)

listdir () 대신 scandir ()를 사용하면 파일 유형 또는 파일 속성 정보가 필요한 코드의 성능을 크게 증가시킬 수 있습니다., os.direntry 객체는 운영 체제가 디렉토리를 스캔 할 때 제공하는 경우이 정보를 노출시키기 때문에이 정보를 노출시킵니다. 모든 os.direntry 메소드는 시스템 호출을 수행 할 수 있지만 is_dir () 및 is_file ()은 일반적으로 기호 링크를위한 시스템 호출 만 필요합니다. os.direntry.stat ()는 항상 UNIX에서 시스템 호출이 필요하지만 Windows의 상징적 링크에만 필요합니다.

파이썬 문서

#import modules
import os

_CURRENT_DIR = '.'


def rec_tree_traverse(curr_dir, indent):
    "recurcive function to traverse the directory"
    #print "[traverse_tree]"

    try :
        dfList = [os.path.join(curr_dir, f_or_d) for f_or_d in os.listdir(curr_dir)]
    except:
        print "wrong path name/directory name"
        return

    for file_or_dir in dfList:

        if os.path.isdir(file_or_dir):
            #print "dir  : ",
            print indent, file_or_dir,"\\"
            rec_tree_traverse(file_or_dir, indent*2)

        if os.path.isfile(file_or_dir):
            #print "file : ",
            print indent, file_or_dir

    #end if for loop
#end of traverse_tree()

def main():

    base_dir = _CURRENT_DIR

    rec_tree_traverse(base_dir," ")

    raw_input("enter any key to exit....")
#end of main()


if __name__ == '__main__':
    main()

fyi 확장자 필터 또는 내선 파일 가져 오기 OS

path = '.'
for dirname, dirnames, filenames in os.walk(path):
    # print path to all filenames with extension py.
    for filename in filenames:
        fname_path = os.path.join(dirname, filename)
        fext = os.path.splitext(fname_path)[1]
        if fext == '.py':
            print fname_path
        else:
            continue
import os, sys

#open files in directory

path = "My Documents"
dirs = os.listdir( path )

# print the files in given directory

for file in dirs:
   print (file)

내가 이것을 던질 것이라고 생각한다면, 와일드 카드 검색을하는 간단하고 더러운 방법.

import re
import os

[a for a in os.listdir(".") if re.search("^.*\.py$",a)]

아래 코드는 DIR 내의 디렉토리 및 파일을 나열합니다.

def print_directory_contents(sPath):
        import os                                       
        for sChild in os.listdir(sPath):                
            sChildPath = os.path.join(sPath,sChild)
            if os.path.isdir(sChildPath):
                print_directory_contents(sChildPath)
            else:
                print(sChildPath)

나는 이것이 오래된 질문이라는 것을 알고 있습니다. 이것은 당신이 liunx 기계에 있다면 내가 만난 깔끔한 방법입니다.

import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))

나와 함께 일한 사람은 위의 Saleh Answer의 수정 된 버전입니다.

코드는 다음과 같습니다.

"dir = 'have_directory_name'filenames = [os.path.abspath (os.path.join (dir, i)) os.listdir (dir)]]]

하는 동안 os.listdir() 파일 목록과 딥 이름 목록을 생성하는 데 괜찮습니다. 자주 해당 이름이 있고 Python3에서 더 많은 일을하고 싶습니다. pathlib 다른 집안일을 간단하게 만듭니다. 내가하는 것만 큼 좋아하는지 살펴보고 봅시다.

DIR 내용을 나열하려면 경로 개체를 구성하고 반복자를 잡습니다.

In [16]: Path('/etc').iterdir()
Out[16]: <generator object Path.iterdir at 0x110853fc0>

사물 이름 목록 만 원한다면 다음과 같습니다.

In [17]: [x.name for x in Path('/etc').iterdir()]
Out[17]:
['emond.d',
 'ntp-restrict.conf',
 'periodic',

Dirs를 원한다면 :

In [18]: [x.name for x in Path('/etc').iterdir() if x.is_dir()]
Out[18]:
['emond.d',
 'periodic',
 'mach_init.d',

해당 트리의 모든 conf 파일의 이름을 원한다면 :

In [20]: [x.name for x in Path('/etc').glob('**/*.conf')]
Out[20]:
['ntp-restrict.conf',
 'dnsextd.conf',
 'syslog.conf',

트리에서 conf 파일 목록을 원한다면> = 1k :

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',

상대 경로 해결이 쉬워집니다.

In [32]: Path('../Operational Metrics.md').resolve()
Out[32]: PosixPath('/Users/starver/code/xxxx/Operational Metrics.md')

경로로 탐색하는 것은 매우 명확합니다 (예상치 못한 경우) :

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'),
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top