I have a folder with up to 1000 files and I want to add a random number to each of the files without repeating any number.
My files look like this:
file_a.jpg
file_b.jpg
file_c.jpg
file_d.jpg
and I want them to be like this:
3_file_a.jpg
1_file_b.jpg
4_file_c.jpg
2_file_d.jpg
This is my code snippet so far, but using random.sample() seems not to be the right solution. At the moment it creates a list of random variables, which are non repeating, but it creates a new list for each filename. Instead of just one non-repeating number per filename. Might be a dumb question, but I am new to python and couldn't figure it out yet how to do this properly.
import os
from os import rename
import random
os.chdir('C:/Users/......')
for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
#file_name = str(random.sample(range(1000), 1)) + '_' + file_name
print(file_name)
new_name = '{}{}'.format(file_name, file_ext)
os.rename(f, new_name)
Aucun commentaire:
Enregistrer un commentaire