With fewer than 100 lines of code, this Python script can rename every file inside a folder, including files buried in nested subfolders. In theory, the recursive approach can keep going indefinitely; in practice, the limit depends on available memory.

It supports two renaming styles:

  1. Replace every original filename with a random 20-character alphanumeric string.
  2. Keep the original name, but add a custom prefix in front of it.

A few practical notes before running it:

  • On Windows, os.getcwd() can be misleading. It returns the working directory of the command window that launched Python, not necessarily the directory where the script itself is stored, so entering the path manually is safer.
  • The folder traversal is implemented with recursion. That makes multi-level nesting easy to handle, but each recursive call also consumes memory.
  • The sample code was tested with Python 3.7.2, 64-bit, on Windows. If you want to run it on Linux, you will need to adjust the path separator logic.

The script skips renaming the currently running .py file, which avoids breaking itself mid-execution.

# 导入系统模块
import os  # 用于文件处理
import random  # 用于生成随机文件名
from pathlib import Path  # 用于获取本文件名


def getAllFiles(filePath=os.getcwd()):
    '''
        递归获取文件夹内所有文件
        filePath:文件夹路径
    '''
    # 获取的当前文件夹路径不是当前文件所在的文件夹路径,而是Python程序运行时CMD窗口所运行的文件夹!
    fileList = os.listdir(filePath)

    # 判断路径为文件还是文件夹
    for file in fileList:
        tempPath = filePath+'\\'+file
        if os.path.isdir(tempPath):
            # 不是文件,进行递归操作
            getAllFiles(tempPath)
        elif os.path.isfile(tempPath):
            # 是文件
            if file != Path(__file__).name:
                # 跳过对当前正在执行的py文件重命名
                fileRename(tempPath)
        else:
            # 特殊无后缀文件
            print("it's a special file(socket,FIFO,device file):"+tempPath)


def fileRename(filePath, myStr=''):
    '''
        对文件进行重命名
        filePath 为文件路径(绝对路径)
        myStr 为模式选择:
            mode = ''时:去除原来的文件名,随机生成一个由大写字母、小写字母和数字组成的20位字符串作为文件名
                例如:TNcxBZEvgZiH9OtqFMWC.jpg、fh4vUsewZ9y8RGBmLKg5.docx
            mode != ''时:在原文件名前追加一个字符串(举例输入为:myStr)
                例如:原文件名为 test.pptx,新文件名为 myStr_test.pptx
    '''

    splitSign = filePath.rfind('\\')  # 获取文件名与路径分隔符位置
    filePathShort = filePath[:splitSign]  # 获取文件所在路径
    fileSuffix = filePath[filePath.rfind(".")+1:]  # 获取文件后缀

    if not myStr:
        # 随机重命名模式
        randomStr = ''.join(random.sample(
            'zyxwvutsrqponmlkjihgfedcbaABCDEFGHIJKLMNOPQRSTUZWXYZ0123456789', 20))  # 生成一个随机字符串(20位)
        os.rename(filePath, filePathShort+'\\' +
                  randomStr+'.'+fileSuffix)  # 重命名操作
    else:
        # 自定义模式
        fileName = filePath[splitSign+1:filePath.rfind(".")]  # 获取文件原名称
        os.rename(filePath, filePathShort+'\\'+myStr + '_' +
                  fileName+'.'+fileSuffix)  # 重命名操作

    # 每重命名一个文件,计数器加1
    global fileNum
    fileNum += 1


def printInfo():
    ''' 打印程序提示 '''
    print('='*40)
    print(' 欢迎使用本程序 '.center(33, '+'))
    print('='*40)
    print("使用须知:")
    print("1. 本程序基于Python 3.7.2 64-bit windows平台;")
    print("2. 输入文件路径中必须以'\\'为分隔符。")
    print('='*40)


# 打印提示信息
printInfo()

# 获取用户输入路径,若为当前路径直接回车
inputFilePath = input("请输入文件夹路径:")

# 定义一个变量用来记录重命名文件数量
fileNum = 0

# 执行程序
if inputFilePath:
    # 用户输入了路径
    getAllFiles(inputFilePath)
else:
    # 用户输入为空,获取默认路径
    getAllFiles()
    inputFilePath = os.getcwd()

# 程序结束,打印结束信息
print(" 程序结束 ".center(36, '='))
print(f" 共对 {fileNum} 个文件完成操作 ".center(31, '='))
print(f"操作文件夹为:{inputFilePath}")

print('='*40)

How the two modes work

The renaming logic lives in fileRename():

  • If myStr is empty, the script generates a 20-character string made from uppercase letters, lowercase letters, and digits, then uses that as the new filename while keeping the original extension.
  • Example output: TNcxBZEvgZiH9OtqFMWC.jpg
  • If myStr is not empty, the script leaves the original name in place and prepends the given string plus an underscore.
  • Example: test.pptx becomes myStr_test.pptx

What the traversal does

getAllFiles() walks through the specified folder one level at a time. When it encounters a directory, it calls itself again on that directory. When it encounters a regular file, it passes the full path to fileRename().

There is also a small safeguard built in: if the file being inspected matches Path(__file__).name, the script skips it so it does not rename the Python file that is currently running.

Path handling on Windows

The script builds file paths using \\, which matches Windows-style paths. That is why manual path entry is recommended, and why a Linux version would need path separator changes.

If you simply press Enter when prompted for a folder path, the program falls back to os.getcwd(). On Windows, that value may point to the directory where the command prompt was started rather than the script's location, so it is worth checking carefully before running bulk renames.

Program output

After completion, the script prints:

  • a closing message,
  • how many files were processed,
  • and the target folder path.

That gives you a quick confirmation of what was changed.

Illustration