Доступ к текстовым файлам с использованием библиотеки os в Python: методы и примеры

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

Метод 1: использование os.path.join()и open()

import os
file_path = os.path.join("path", "to", "file.txt")
try:
    with open(file_path, "r") as file:
        content = file.read()
        # Do something with the file content
except FileNotFoundError:
    print("File not found.")

Метод 2: использование os.listdir()и open()

import os
directory = "path/to/directory"
try:
    files = os.listdir(directory)
    for file_name in files:
        if file_name.endswith(".txt"):
            file_path = os.path.join(directory, file_name)
            with open(file_path, "r") as file:
                content = file.read()
                # Do something with the file content
except FileNotFoundError:
    print("Directory not found.")

Метод 3: использование os.scandir()и open()

import os
directory = "path/to/directory"
try:
    with os.scandir(directory) as entries:
        for entry in entries:
            if entry.is_file() and entry.name.endswith(".txt"):
                file_path = os.path.join(directory, entry.name)
                with open(file_path, "r") as file:
                    content = file.read()
                    # Do something with the file content
except FileNotFoundError:
    print("Directory not found.")

Эти методы демонстрируют различные способы доступа к текстовому файлу с помощью библиотеки osв Python.