Чтобы перебирать файлы в каталоге с помощью Python, вы можете использовать различные методы. Вот несколько подходов:
Метод 1: os.listdir()
import os
directory = 'path/to/directory'
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
# Perform operations on the file
Метод 2: glob.glob()
import glob
directory = 'path/to/directory'
for file_path in glob.glob(directory + '/*'):
if os.path.isfile(file_path):
# Perform operations on the file
Метод 3: os.scandir() (Python 3.5+)
import os
directory = 'path/to/directory'
with os.scandir(directory) as entries:
for entry in entries:
if entry.is_file():
# Perform operations on the file
Метод 4: pathlib.Path() (Python 3.4+)
from pathlib import Path
directory = Path('path/to/directory')
for file_path in directory.iterdir():
if file_path.is_file():
# Perform operations on the file
Эти методы позволяют перебирать файлы в указанном каталоге. Не забудьте заменить 'path/to/directory'фактическим путем к каталогу, через который вы хотите пройти.