Programming

파이썬에서 디렉토리의 내용을 어떻게 나열합니까?

procodes 2020. 6. 5. 22:24
반응형

파이썬에서 디렉토리의 내용을 어떻게 나열합니까?


어려울 수는 없지만 정신적 장애가 있습니다.


import os
os.listdir("path") # returns list

일방 통행:

import os
os.listdir("/home/username/www/")

다른 방법 :

glob.glob("/home/username/www/*")

여기에 예가 있습니다 .

glob.glob방법은 숨겨진 파일을 나열하지 않습니다.

몇 년 전에이 질문에 원래 답변 했으므로 pathlib 가 Python에 추가되었습니다. 디렉토리를 나열하는 선호하는 방법은 일반적 iterdir으로 Path객체에 대한 메소드와 관련이 있습니다.

from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")

os.walk 재귀가 필요한 경우 사용할 수 있습니다.

import os
start_path = '.' # current directory
for path,dirs,files in os.walk(start_path):
    for filename in files:
        print os.path.join(path,filename)

glob.glob아니면 os.listdir할 것입니다.


os모듈 핸들 모든 물건.

os.listdir(path)

경로로 주어진 디렉토리에있는 항목의 이름이 포함 된 목록을 반환하십시오. 목록은 임의의 순서입니다. 특수 항목 '.'은 포함되지 않습니다. 그리고 디렉토리에 존재하더라도 '..'.

가용성 : 유닉스, Windows.


Python 3.4 이상에서는 새로운 pathlib패키지를 사용할 수 있습니다 .

from pathlib import Path
for path in Path('.').iterdir():
    print(path)

Path.iterdir()이터레이터를 반환합니다 list.

contents = list(Path('.').iterdir())

Python 3.5부터 사용할 수 있습니다 os.scandir.

차이점은 이름이 아닌 파일 항목을 반환한다는 것 입니다. Windows와 같은 일부 OS os.path.isdir/file에서는 파일인지 여부를 알 필요가 없으며 statWindows에서 dir을 스캔 할 때 이미 수행되어 CPU 시간을 절약 합니다.

디렉토리를 나열하고 max_value바이트 보다 큰 파일을 인쇄하는 예 :

for dentry in os.scandir("/path/to/dir"):
    if dentry.stat().st_size > max_value:
       print("{} is biiiig".format(dentry.name))

( 여기 에서 광범위한 성능 기반 답변을 읽으 십시오 )


아래 코드는 디렉토리 내의 디렉토리와 파일을 나열합니다. 다른 하나는 os.walk입니다

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)

참고 URL : https://stackoverflow.com/questions/2759323/how-can-i-list-the-contents-of-a-directory-in-python

반응형