python - 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)
解决方案
您可以在所需目录中找到文件,然后随机排列索引列表以与文件配对:
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']
推荐阅读
- jestjs - Jest 和 NestJs 如何关闭 prisma 连接
- javascript - 未捕获的类型错误:无法添加属性 0,对象在 Array.push 中不可扩展
- ssh - rsync 成功或失败取决于目标目录
- docker - Docker 错误没有这样的容器。不过好像没问题
- r - 处理超过 24 小时的时间格式并做一些数学运算
- reactjs - 如何在没有额外请求的情况下提供数据以与 drf 做出反应?
- c++ - 自制 OpenCV pkg-config CMake
- c - Gstreamer C code for adding extra-header tokens in souphttpsrc
- mongodb - mongoDB matching localdatetime when using aggregation
- python - How can I create a sequence of repeating numbers based on another column in python?