Randomly Rename Files in Directory

  • Share this:

Code introduction


This function takes a directory path as an argument and then renames all files in the directory randomly.


Technology Stack : os, random

Code Type : File operation

Code Difficulty : Intermediate


                
                    
import os
import sys
import random

def shuffle_file_names(directory):
    """
    随机重命名指定目录下的文件名
    """
    files = os.listdir(directory)
    for i in range(len(files)):
        os.rename(os.path.join(directory, files[i]), os.path.join(directory, f"{random.randint(0, 1000)}.txt"))                
              
Tags: