Hackerss.com

Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in
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

Top comments (0)