mercredi 26 juillet 2023

How do I take original files in one directory, shuffle the names to be randomized for the actual file, and move them without overwriting

I am working on taking the names of daily email list files for one week and randomizing the names/days of the files for the next week to where they wont get contacted on the same day of the week. I've been using random.choice() with the directory to change the name of the file to one of the existing ones in the original folder and moving it to a new folder, but when I get to the third or fourth file it either overwrites or stops completely.

import os
import random
import shutil

def shuffle_and_move_files(source_folder, destination_folder):
    if not os.path.exists(source_folder):
        print(f"Source folder '{source_folder}' does not exist.")
        return

    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    files_list = os.listdir(source_folder)
    random.shuffle(files_list)

    for filename in files_list:
        source_path = os.path.join(source_folder, filename)
        if os.path.isfile(source_path):

            random_name = random.choice(file_list)
            
            destination_path = os.path.join(destination_folder, random_name)
            
            shutil.move(source_path, destination_path)
            
            print(f"Moved '{filename}' to '{random_name}'")



Aucun commentaire:

Enregistrer un commentaire