3

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)
2
  • 1
    Why not for i, f in enumerate(os.listdir()):. That way you have both and it's pythonic. Do you want this numbers to be in a random order? Commented Sep 17, 2018 at 15:08
  • You could use uuid (Universally Unique IDentifier) for the random number. import uuid and then something like new_name = '{}_{}'.format(uuid.uuid4(), f). Commented Sep 17, 2018 at 17:11

2 Answers 2

3

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']
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.