Skip to main content

chat1

import contextlib
import itertools

# List of file paths to open
file_paths = ["file1.txt", "file2.txt", "file3.txt"]

# Function to process lines as if they come from one file
def process_lines(lines):
    for line in lines:
        print(line.strip())

# Open multiple files and chain their lines together
with contextlib.ExitStack() as stack:
    files = [stack.enter_context(open(file_path, 'r')) for file_path in file_paths]
    
    # Chain the file line iterators together
    all_lines = itertools.chain.from_iterable(file for file in files)
    
    # Pass the chained iterator to the function
    process_lines(all_lines)