Associating PNG FileNames With JSON FileNames and Randomizing

24 views Asked by At

I have PNG and JSON files on a folder whose names are numbered from 1 to 1000. In other words, I have 2000 files. The PNG files match the JSON files by the number in their names. For example, the information of 15.png is in 15.json. What I want to do is randomly rename these files while maintaining the association of the png files to the json files. For instance, I would like to rename 15.png to 321.png and that would mean renaming 15.json to 321.json. To prevent using a number that is already in the folder, it would be better to copy both the png and its json to a new folder and then assigning a random number/name (between 1 and 1000) for both files and repeating the process. I have tried using the .split, .startswith and . endwith functions but am having difficulty. Any insight is much appreciated.

1

There are 1 answers

0
gunnar On

I can't tell if this is the most elegant or performant way to do it, but you could try the following:

# Import some modules from the standard library
import pathlib
import random
import shutil


# Specify the directory that contains your original files.
data_directory = pathlib.Path('./')

# Specify the name of the directory where the renamed files are going
# to be stored.
new_directory = pathlib.Path('./new')

# Create the new directory, if it does not exist, yet.
new_directory.mkdir(exist_ok=True)

# Create a list of all png files in the directory given above using a
# list comprehension.
# Pitfall: Please note that the suffix attribute contains a leading dot,
# i.e. using suffix == 'png' would return an empty list.
original_files = [
    item for item in data_directory.iterdir()
    if item.suffix == '.png'
]

# Create a copy of your list of files and shuffle it randomly.
new_names = original_files.copy()
random.shuffle(new_names)

# Loop over both file lists simultaneously and get the name of the file
# to copy from the first one, and derive it's destination from the second 
# one.
for old, new in zip(original_files, new_names):
    shutil.copy(old, new_directory.joinpath(new))

To move your json files too, you only have to add one line to the loop, but I'll leave it to you to figure that one out. It involves the .with_suffix-method that is available on Path-objects.