Rick
Rick

Reputation: 31

Python: Add random number to filename (without repeating a number)

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)

Upvotes: 3

Views: 2039

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

You can find the files in your desired directory, and then shuffle a list of indices to pair with the files:

import os, random
_files = os.listdir()
vals = list(range(1, len(_files)+1))
random.shuffle(vals)
new_files = [f'{a}_{b}' for a, b in zip(vals, _files)]

Sample output (running on my machine):

['24_factorial.s', '233_familial.txt', '15_file', '96_filename.csv', '114_filename.txt', '190_filename1.csv', '336_fingerprint.txt', '245_flask_essentials_testing', '182_full_compression.py', '240_full_solution_timings.py', '104_full_timings.py']

Upvotes: 3

vash_the_stampede
vash_the_stampede

Reputation: 4606

If you create a list to store the used randints you can then use a while loop to ensure you get no repeats

import os
import random

used_random = []

os.chdir('./stack_overflow/test')
for filename in os.listdir():
    n = random.randint(1, len(os.listdir()))
    while n in used_random:
        n = random.randint(1, len(os.listdir()))
    used_random.append(n)
    os.rename(filename, f"{n}_{filename}")

Before:

(xenial)vash@localhost:~/python/stack_overflow/test$ ls
file_a.py  file_b.py  file_c.py  file_d.py  file_e.py

After:

(xenial)vash@localhost:~/python/stack_overflow/test$ ls
1_file_b.py  2_file_e.py  3_file_a.py  4_file_c.py  5_file_d.py

Upvotes: 3

Related Questions