124 of 151 menu

The rename method of the os module

The rename method renames and/or moves a file or folder. In the first parameter of the method we specify the original path to the file or folder, in the second parameter - the new path or file name/folders. In the second and third optional parameters, we can specify the file descriptor of the source and destination paths, respectively. The method returns None. If the file we want to rename does not exist, the method returns the exception FileNotFoundError.

Syntax

import os os.rename(original path, new path, [source path file descriptor], [file descriptor of the new path])

Example

Let's rename the folder dir1:

import os os.rename('dir1', 'dir2')

Example

Now let's rename the file:

import os os.rename('file1.txt', 'file2.txt')

See also

  • method makedirs of module os,
    which creates a directory
  • method remove of module os,
    which deletes the file
  • method getcwd module os,
    which returns the current working directory
  • method listdir of module os,
    which returns a list of files in the working directory
  • method path.isdir of module os,
    which checks the existence of a folder
  • method path.isfile of module os,
    which checks the existence of a file
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline