P
P
PosikGG2021-07-26 13:39:41
Python
PosikGG, 2021-07-26 13:39:41

Why doesn't Python shuffle the list of files?

I wrote the code to make the program shuffle the music on the flash drive. It renames all files to random numbers, and then in order: "1, 2, 3, ...".
If you do only the first stage (Rename to random numbers), then the files are mixed, but when the program renames them in order (B 1, 2, 3, ...), then they return to the previous order.

I deleted the part that renames in order. I can't figure out how to do it anymore.

import os
import random

def rename():
    global path, i, ext, abs_file_name

    try:
        new_abs_file_name = os.path.join(path, str(i) + ext)
        os.rename(abs_file_name, new_abs_file_name)
        
    except FileExistsError:
        i = random.randint(1000, 1000000)
        rename()

path = "F:"   
path  =  rf"{path}"

i = random.randint(1000, 100000)

for file_name in os.listdir(path):
    base_name, ext = os.path.splitext(file_name)

    if ext.lower() not in ['.mp3']:
        continue

    abs_file_name = os.path.join(path, file_name)

    rename()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-07-26
@PosikGG

First, don't use global unless absolutely necessary.
Secondly, it can be done many times easier.

import glob
import os
import random

# обрабатываемый каталог
path = r'F:'
# абсолютные пути ко всем mp3 файлам в каталоге
mp3files = [os.path.abspath(filename) for filename in glob.glob(os.path.join(path, '*.mp3'))]
# перемешиваем
random.shuffle(mp3files)
# переименуем каждый файл в его номер, но с префиксом _
# это нужно чтобы не было конфликтов 
# (так как 1.mp3 уже есть в папке после предыдущего запуска программы)
for i,filename in enumerate(mp3files, 1): #нумерация с 1 а не с 0
    base = os.path.basename(filename) #имя файла
    # программа не сохранит предыдущие названия файлов. Сделать это сложнее.
    os.rename(filename, os.path.join(path, f'_{i}.mp3'))
# теперь уберём префикс - переименуем _1.mp3 в 1.mp3
for i in range(1, len(mp3files)+1): #нумерация с 1
  os.rename(os.path.join(path, f'_{i}.mp3'), os.path.join(path, f'{i}.mp3'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question