Чтобы открыть два файла в Python с помощью оператора with, вы можете использовать следующие методы:
Метод 1: использование нескольких операторов with
with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2:
# Perform operations on file1 and file2
# Example:
data1 = file1.read()
data2 = file2.read()
Метод 2. Использование списка путей к файлам
file_paths = ['file1.txt', 'file2.txt']
with [open(file_path, 'r') for file_path in file_paths] as files:
file1, file2 = files # Assign each file to a variable
# Perform operations on file1 and file2
# Example:
data1 = file1.read()
data2 = file2.read()
Метод 3. Использование вложенного оператора with
with open('file1.txt', 'r') as file1:
with open('file2.txt', 'r') as file2:
# Perform operations on file1 and file2
# Example:
data1 = file1.read()
data2 = file2.read()
Эти методы позволяют открывать несколько файлов с помощью оператора with, что гарантирует правильное закрытие файлов после завершения работы с ними, даже если возникнет исключение.