파이썬에서 디렉토리의 내용을 어떻게 나열합니까?
어려울 수는 없지만 정신적 장애가 있습니다.
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
에서는 파일인지 여부를 알 필요가 없으며 stat
Windows에서 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
'Programming' 카테고리의 다른 글
상태가 검토 대기중인 2 진 거부 (2 진 거부 단추를 찾을 수 없음) (0) | 2020.06.05 |
---|---|
파이썬 형식 문자열에서 % s는 무엇을 의미합니까? (0) | 2020.06.05 |
C ++ 문자열 (또는 char *)을 wstring (또는 wchar_t *)으로 변환 (0) | 2020.06.05 |
IntelliJ 프로젝트에 Gradle 지원을 추가하는 가장 좋은 방법 (0) | 2020.06.05 |
JavaScript에서 부모 Iframe에 액세스하는 방법 (0) | 2020.06.05 |