
지정된 디렉터리의 파일 반복
특정 디렉터리 내의 파일을 작업할 때는 해당 파일을 효율적으로 반복해야 합니다. 다음은 Python에서 이 작업을 수행하기 위한 단계별 가이드입니다.
os 모듈 사용:
os 모듈은 Python과 상호 작용하기 위한 포괄적인 기능 세트를 제공합니다. 운영 체제. 특정 디렉토리 내의 파일을 반복하려면 다음 코드를 활용하십시오.
1 2 3 4 5 6 7 8 9 10 11 | import os
# Replace '/path/to/dir/' with your actual directory path
directory = '/path/to/dir/'
# Loop through the files in the directory
for filename in os.listdir(directory):
# Check if the file has the desired extension
if filename.endswith( '.asm' ):
# Perform desired actions on the file
pass
|
로그인 후 복사
pathlib 모듈 사용:
pathlib 모듈은 보다 객체 지향적인 접근 방식을 제공합니다. 파일 처리를 위해. pathlib를 사용하여 파일을 반복하는 방법은 다음과 같습니다.
1 2 3 4 5 6 7 8 9 10 11 12 | from pathlib import Path
# Replace '/path/to/dir/' with your actual directory path
directory = '/path/to/dir/'
# Create a Path object for the directory
path = Path(directory)
# Iterate over the files in the directory
for file in path. glob ( '**/*.asm' ):
# Perform desired actions on the file
pass
|
로그인 후 복사
위 내용은 Python의 특정 디렉터리에 있는 파일을 효율적으로 반복하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!