Shuffle Files in Directory to Output File

  • Share this:

Code introduction


This function shuffles all files in a specified directory and saves the sorted file names to a specified output file.


Technology Stack : os, random

Code Type : File operation

Code Difficulty : Intermediate


                
                    
import os
import sys
import random

def shuffle_files(directory, output_file):
    """
    Shuffle files in a directory and save them to a new file.
    """
    files = os.listdir(directory)
    random.shuffle(files)
    with open(output_file, 'w') as f:
        for file in files:
            f.write(file + '\n')
    return output_file                
              
Tags: