How to rename a file using Python


Question

I want to change a.txt to b.kml.

1
277
10/10/2012 1:29:30 PM

Accepted Answer

Use os.rename:

import os

os.rename('a.txt', 'b.kml')
477
3/28/2018 1:39:29 PM

File may be inside a directory, in that case specify the path:

import os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon