3

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?

CosimoCD
  • 3,570
  • 3
  • 22
  • 31
  • Do you know the file names in advance, or are you reading them from a directory? Could you elaborate on what exactly you're trying to achieve? – Mureinik Oct 17 '16 at 10:27
  • It's not quite clear what your actual problem is. Finding pairs of file names? Opening the files? Here's how to open multiple files at once using `with`: http://stackoverflow.com/questions/4617034/how-can-i-open-multiple-files-using-with-open-in-python/4617069#4617069 – Sven Marnach Oct 17 '16 at 10:28
  • Yes I know the file names in advance. They are series of couple with the same name but different extension. I have to open couple by couple that have the same name but different extension. – CosimoCD Oct 17 '16 at 10:30
  • I already saw the link above but it doesn't work because i use a for loop on multiple files and i can't write the file name evry time. – CosimoCD Oct 17 '16 at 10:38

2 Answers2

3

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)
mhawke
  • 84,695
  • 9
  • 117
  • 138
0

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)