Hackerss.com

hackerss
hackerss

Posted on

Rename a file in Python

Rename a file - Python:


import os

def rename_file(file_name, new_name):
    """
    Rename a file.

    Parameters
    ----------
    file_name : str
        The name of the file to rename.
    new_name : str
        The new name of the file.

    Returns
    -------
    bool
        ``True`` if the file was renamed, ``False`` otherwise.
    """

    #check if the file exists
    if os.path.exists(file_name):
        #rename the file
        os.rename(file_name, new_name)
        return True
    else:
        return False

#example
rename_file('test.txt', 'new_test.txt')
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)