首页 > 解决方案 > 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)

标签: pythonrandom

解决方案


您可以在所需目录中找到文件,然后随机排列索引列表以与文件配对:

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)]

示例输出(在我的机器上运行):

['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']

推荐阅读