How to open concurrently two files with same name and different extension in python?

file, io, python-2.7

Solution

You could do something like the following which constructs a dictionary keyed by the file name sans extension, and with a count of the number of files matching the required extensions. Then you can iterate over the dictionary opening pairs of files:

import os
from collections import defaultdict

EXTENSIONS = {'.json', '.txt'}

directory = '/path/to/your/files'

grouped_files = defaultdict(int)

for f in os.listdir(directory):
    name, ext = os.path.splitext(os.path.join(directory, f))
    if ext in EXTENSIONS:
        grouped_files[name] += 1

for name in grouped_files:
    if grouped_files[name] == len(EXTENSIONS):
        with open('{}.txt'.format(name)) as txt_file, \
                open('{}.json'.format(name)) as json_file:
            # process files
            print(txt_file, json_file)

Problem

I have a folder with multiple couple of files: ``` a.txt a.json b.txt b.json ``` and so on: Using a for loop i want to open a couple of file (a.txt and a.json) concurrently. Is there a way to do it using the 'with' statement in python?

Original source

Related problems