Python – 디렉터리의 파일 나열

ItsMyCode |

파이썬에는 디렉터리나 폴더의 파일을 나열하는 데 사용할 수 있는 여러 모듈이 있습니다. 우리가 사용할 수 있는 대중적인 것들 중 일부는 os, pathlib, glob, fnmatch 등입니다. 이 튜토리얼에서는 디렉토리에 있는 모든 파일을 나열하는 가장 인기 있는 방법을 살펴볼 것입니다.

방법 1: os.listdir() 메서드 사용


os.listdir()를 사용하여 지정된 경로의 모든 파일과 디렉토리를 가져올 수 있습니다.

구문 – os.listdir(경로)

경로를 매개변수로 사용하고 지정된 경로의 모든 파일 및 디렉토리 목록을 반환합니다.

# import OS module
import os

# List all the files and directories
path = "C:\Projects\Tryouts"
dir_list = os.listdir(path)

print("Files and directories in '", path, "' :")

# prints all files
print(dir_list)



산출

Files and directories in ' C:\Projects\Tryouts ' :
['calc.py', 'etc', 'listindexerror.py', 'main.py', 'Python Tutorial.py', 'Python Tutorial.txt', 'test', 'test - Copy', ' __pycache__']


방법 2: os.walk() 메서드 사용



os 모듈은 운영 체제 기능과 상호 작용하는 많은 기능을 제공하며 그러한 방법 중 하나는 디렉토리 트리에서 파일 및 폴더를 생성하는 os.walk() 입니다. 하향식 또는 상향식 검색으로 트리를 탐색할 수 있으며 기본적으로 하향식 검색으로 설정됩니다.
os.walk()는 절대 경로에서 파일 및 폴더를 검색하는 데도 도움이 됩니다.

# import OS module
import os

# List all the files and directories
path = "C:\Projects\Tryouts"
for (root, directories, files) in os.walk(path, topdown=False):
    for name in files:
        print(os.path.join(root, name))
    for name in directories:
        print(os.path.join(root, name))


산출

C:\Projects\Tryouts\etc\password.txt
C:\Projects\Tryouts\test\python.txt
C:\Projects\Tryouts\test - Copy\python.txt
C:\Projects\Tryouts\ __pycache__ \calc.cpython-39.pyc
C:\Projects\Tryouts\calc.py
C:\Projects\Tryouts\listindexerror.py
C:\Projects\Tryouts\main.py
C:\Projects\Tryouts\Python Tutorial.py
C:\Projects\Tryouts\Python Tutorial.txt
C:\Projects\Tryouts\etc
C:\Projects\Tryouts\test
C:\Projects\Tryouts\test - Copy
C:\Projects\Tryouts\ __pycache__


방법 3: os.scan() 메서드 사용


os.scan() 메서드는 Python 3.5 이상에서 사용할 수 있습니다. scandir()는 경로 매개변수에 대해 bytes 또는 str 객체를 허용하고 경로와 동일한 유형의 DirEntry.name 및 DirEntry.path 속성을 반환합니다.

구문: os.scandir(경로 = '.')

# import OS module
import os

# List all the files and directories
path = "C:\Projects\Tryouts"
data = os.scandir()

for item in data:
    if item.is_dir() or item.is_file():
        print(item.name)


산출

calc.py
etc
listindexerror.py
main.py
Python Tutorial.py
Python Tutorial.txt
test
test - Copy
__pycache__


방법 4: glob 모듈 사용


glob 모듈은 glob이 와일드카드 검색을 지원하므로 지정된 패턴과 일치하는 파일/경로를 검색하는 데 도움이 됩니다. glob 모듈을 사용하여 파일과 폴더를 모두 가져올 수 있습니다.

# import OS module
import glob

# List all the files and directories
path = "C:\Projects\Tryouts\*"

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

C:\Projects\Tryouts\calc.py
C:\Projects\Tryouts\etc
C:\Projects\Tryouts\listindexerror.py  
C:\Projects\Tryouts\main.py
C:\Projects\Tryouts\Python Tutorial.py 
C:\Projects\Tryouts\Python Tutorial.txt
C:\Projects\Tryouts\test
C:\Projects\Tryouts\test - Copy
C:\Projects\Tryouts\ __pycache__

iglob() 메서드를 사용하여 파일 이름을 재귀적으로 인쇄할 수도 있습니다. 재귀 매개변수를 true로 설정하기만 하면 됩니다.

아래 예에서는 재귀가 true로 설정되고 특정 패턴으로 검색하여 iglob() 메서드를 사용하여 모든 .py 파일을 가져옵니다.

# import OS module
import glob

# List all the files and directories
path = "C:\Projects\Tryouts\*.py"

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


산출

C:\Projects\Tryouts\calc.py
C:\Projects\Tryouts\listindexerror.py 
C:\Projects\Tryouts\main.py
C:\Projects\Tryouts\Python Tutorial.py


게시물 Python – List Files in a DirectoryItsMyCode에 처음 나타났습니다.

좋은 웹페이지 즐겨찾기