CosimoCD
CosimoCD

Reputation: 3760

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

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?

Upvotes: 3

Views: 4767

Answers (2)

damanpreet singh
damanpreet singh

Reputation: 119

i have two folders of diffrent files one with .jpg and another with.xml this is how i put them into another folder

import os
from pathlib import Path
import shutil

#making the list to store the name
picList=list()
xmlList=list()


#making the directory path
xmlDir = os.listdir('C:\\Users\\%USERNAME%\\Desktop\\img+xml\\XML')
picDir=os.listdir('C:\\Users\\%USERNAME%\\Desktop\\img+xml\\img')
dest=r'C:\Users\%USERNAME%\Desktop\img+xml\i'


#appending the file name to the list
for a in xmlDir:
    a=Path(a).stem
    xmlList.append(a)
    picList.append(a)


#matching and putting file name in destination
for a in xmlList:
    for b in picList:
        if a==b:
            try:
                shutil.move(f'C:\\Users\\%USERNAME%\\Desktop\\img+xml\\XML\\{a}.xml',dest)
                shutil.move(f'C:\\Users\\%USERNAME%\\Desktop\\img+xml\\img\\{b}.jpg',dest)
            except Exception as e:
                        print(e)
       

Upvotes: 0

mhawke
mhawke

Reputation: 87054

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)

Upvotes: 3

Related Questions