Методы Python для чтения папки с примерами кода

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

  1. Использование модуля os:

    import os
    folder_path = '/path/to/folder'
    # List all files and directories in the folder
    files = os.listdir(folder_path)
    # Print file names
    for file in files:
    print(file)
  2. Использование модуля glob (для сопоставления с образцом):

    import glob
    folder_path = '/path/to/folder'
    # List all files with a specific extension (e.g., .txt files)
    files = glob.glob(folder_path + '/*.txt')
    # Print file names
    for file in files:
    print(file)
  3. Использование модуля pathlib (Python 3.4+):

    from pathlib import Path
    folder_path = Path('/path/to/folder')
    # List all files and directories in the folder
    files = folder_path.iterdir()
    # Print file names
    for file in files:
    print(file.name)
  4. Использование функции scandir() (Python 3.5+):

    import os
    folder_path = '/path/to/folder'
    # List all files and directories in the folder
    with os.scandir(folder_path) as entries:
    for entry in entries:
        print(entry.name)
  5. Использование функции os.walk():

    import os
    folder_path = '/path/to/folder'
    # Recursively traverse through all files and directories
    for root, dirs, files in os.walk(folder_path):
    # Print directories
    for dir in dirs:
        print(os.path.join(root, dir))
    # Print files
    for file in files:
        print(os.path.join(root, file))