0

I have 2 directories, one with .json and one with .png files. I need to check if the png has a json file in the second folder with the same name and if yes, i need to put that png in a third folder.

I need to make a Python script (3.7) for doing that. Since I don't use Python usually I have a problem of implementing that. Also the names of files saved to the third directory should be saved as increasing numbers ("1.png", "2.png", "3.png" ...).

My idea was to do something like this:

import os

for name in os.listdir(directory):
    for filename in os.listdir(directory2):
        # checking if filename in directory2 with the name from the first directory
        # if the name is same, save it in the third directory
        # else continue

Is it possible to implement that with the os library because I didn't find a solution for that. If not, how can I solve this?

Snowflake
  • 49
  • 1
  • 7
  • 1
    Yes you can do with functions within os. Checkout this post:https://stackoverflow.com/questions/678236/how-to-get-the-filename-without-the-extension-from-a-path-in-python BTW do not use double layer loop. Use a dictionary. – Bing Wang Feb 21 '21 at 22:43

1 Answers1

1

You can use os and shutil:

import os
import shutil

dir1 = '<path of the folder>'
dir2 = '<path of the folder>'
dir3 = '<path of the folder>'

# Create destination folder
os.makedirs(dir3, exist_ok=True)

i = 1
for filename in next(os.walk(dir1))[2]:
    fname, extension = os.path.splitext(filename)
    if extension == '.png' and os.path.exists(os.path.join(dir2, f'{fname}.json')):
        shutil.copyfile(os.path.join(dir1, filename), os.path.join(dir3, f'{i}.png'))
        i += 1
PieCot
  • 3,564
  • 1
  • 12
  • 20