Методы открытия каталога и чтения файлов в Python

Чтобы открыть каталог и прочитать файлы в Python, существует несколько подходов. Вот несколько методов, которые вы можете использовать:

  1. Метод 1: модуль ОС

    import os
    directory = '/path/to/directory'
    for filename in os.listdir(directory):
       if os.path.isfile(os.path.join(directory, filename)):
           with open(os.path.join(directory, filename), 'r') as file:
               # Process the file content
               content = file.read()
               # Do something with the content
  2. Метод 2: модуль glob

    import glob
    directory = '/path/to/directory'
    files = glob.glob(directory + '/*')
    for file in files:
       if os.path.isfile(file):
           with open(file, 'r') as file:
               # Process the file content
               content = file.read()
               # Do something with the content
  3. Метод 3: модуль pathlib (Python 3.4+)

    from pathlib import Path
    directory = Path('/path/to/directory')
    for file in directory.iterdir():
       if file.is_file():
           with open(file, 'r') as file:
               # Process the file content
               content = file.read()
               # Do something with the content

Эти методы позволяют открыть каталог, перебирать файлы в нем и читать их содержимое. Затем вы можете обработать контент в соответствии с вашими требованиями.