I want to change a.txt
to b.kml
.
17 Answers
Use os.rename
:
import os
os.rename('a.txt', 'b.kml')
Usage:
os.rename('from.extension.whatever','to.another.extension')
-
130Should be noted that if the files are not in the working directory you will need the full path. – EndermanAPM Mar 29 '17 at 11:34
-
1not really, on 3.7 ubuntu, works for me using relative paths – toing_toing Feb 28 '19 at 15:51
-
5@toing_toing of course it works, he probably just means that you should be aware of the current directory, and either specify the path relative to it, or just use the absolute path (like `C:/folder/file.txt` on Windows or `/home/file.txt` on Linux/MacOS). – Alex P. Jun 26 '19 at 14:24
-
3It's worth noting that this will silently overwrite files on Unix-like systems but fail with `OSError` on Windows systems. `os.path.exists` should be used to check if the target exists before renaming. This does create a "Time Of Check to Time Of Use" bug, but it's unlikely to cause issues. (I know of no easy way around this - see [here](https://stackoverflow.com/questions/3222341/how-to-rename-without-race-conditions). – AnnanFay Sep 28 '19 at 16:59
-
7If the user actually wants the file to be replaced on any operating system, one should use `os.replace` – LucG Apr 29 '20 at 09:11
-
`os.rename` only works if source and destination are on the same file system. If you are on the differrent file system you should use `shutil.move` instead. – cthemudo Jan 26 '21 at 06:58
-
1@AnnanFay `FileExistsError` is raised now instead of `OSError` when trying to overwrite the destination. Check out [this answer](https://stackoverflow.com/a/68733161/10792235) for using `os.replace` instead as suggested by @LucG – Chris Collett Aug 10 '21 at 20:37
-
for file I guess `rename` is the bad idea to change the extension of a file I have rename pdf file to docx file by this method but it cause problem while opening renamed file – Azhar Uddin Sheikh Sep 07 '21 at 18:10
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)

- 121,510
- 29
- 395
- 339

- 2,654
- 2
- 18
- 24
As of Python 3.4 one can use the pathlib module to solve this.
If you happen to be on an older version, you can use the backported version found here
Let's assume you are not in the root path (just to add a bit of difficulty to it) you want to rename, and have to provide a full path, we can look at this:
some_path = 'a/b/c/the_file.extension'
So, you can take your path and create a Path
object out of it:
from pathlib import Path
p = Path(some_path)
Just to provide some information around this object we have now, we can extract things out of it. For example, if for whatever reason we want to rename the file by modifying the filename from the_file
to the_file_1
, then we can get the filename part:
name_without_extension = p.stem
And still hold the extension in hand as well:
ext = p.suffix
We can perform our modification with a simple string manipulation:
Python 3.6 and greater make use of f-strings!
new_file_name = f"{name_without_extension}_1"
Otherwise:
new_file_name = "{}_{}".format(name_without_extension, 1)
And now we can perform our rename by calling the rename
method on the path object we created and appending the ext
to complete the proper rename structure we want:
p.rename(Path(p.parent, new_file_name + ext))
More shortly to showcase its simplicity:
Python 3.6+:
from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))
Versions less than Python 3.6 use the string format method instead:
from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))

- 25,487
- 7
- 64
- 83
-
7Why would you do this instead of the accepted answer? Seems far more complicated – rbennell Sep 07 '17 at 13:14
-
52Well @rbennell, most of this answer is an explanation. The answer is really just the three lines at the end. Furthermore, the accepted answer is made explicitly for that very name change. This answer provides a way to show how you can manipulate the filename to preserve parts that you want in the path or name of the file. Furthermore, the `pathlib` library is introduced in python 3.4 so sharing the answer here also provides exposure for a solid module to showcase its versatility and usage for more complicated requirements. – idjaw Sep 07 '17 at 13:22
-
9Thank you @idjaw, your comment is a good answer to a basic question of us beginners, a simple _Why did you did that?_. Also, it is refreshing to see non-hostile approach on internet to what is often considered as ignorant. – Igor V. Apr 26 '18 at 05:33
-
can you explain line : `new_file_name = "{}_{}".format(name_without_extension, 1)` ? What is `{}_{}` ? where can I read more about it? – Sasuke Uchiha May 05 '18 at 15:16
-
3@SasukeUchiha - The `{}` are for string formatting, which you can read about [here](https://docs.python.org/3.7/library/string.html#format-examples). Ultimately, what is happening is that the `{}` get replaced with the variables that are passed in to the `format` method. So the first `{}` will hold what is in `name_without_extension`, and the second will hold the second argument which is simply `1`. – idjaw May 05 '18 at 19:07
-
1In addition to the python docs. http://pyformat.info has lots of easy to read explanations and examples of all kinds of python string formatting – prooffreader Feb 10 '19 at 18:07
-
4Using f-strings simplifies it even more. from pathlib import Path p = Path(some_path) version = 1 p.rename(Path(p.parent, f"{p.stem}_{version}" + p.suffix)) – Liquidgenius May 04 '19 at 16:17
-
1+1 for f-strings @idjaw can you add them in so that others can benefit ? :) thanks for the awesome post. – Umar.H Sep 18 '19 at 17:21
-
@Datanovice Thanks for the edit and ping. I was meaning to update this and forgot. Cheers. – idjaw Sep 18 '19 at 18:05
-
Just best to put both, however, because it is still quite likely people might not be necessarily on Python 3.6. – idjaw Sep 18 '19 at 18:11
-
1That's fine, your post helped me solve some complex I/O operations at work. My thanks to you for helping the community! – Umar.H Sep 18 '19 at 20:14
-
It seems like ugly code to me because you need to create two `Path` objects:`# first_one p = Path(some_path) p.rename(# second_one Path(p.parent, f"{p.stem}_1_{p.suffix}"))` – Timo Feb 16 '22 at 11:02
-
Great answer :). A minor simplification: `p.rename(p.parent / f"{p.stem}_1_{p.suffix}")` works too since `p.parent` is already a Path instance. – Javier TG Sep 28 '22 at 11:32
-
Thing to keep in mind about complexity of `path` to `os.rename` is that, in the os rename case you already have to know the new name. If that requires substantial calculation (which is not the case in this Q) then you will have to do it yourself, which is not always easy when paths are concerned. On the other hand pathlib provides many name manipulation facilities. Note that `Path("a.txt").rename("b.kml")` is **all you really need to do what OP was asking for**. – JL Peyret Dec 01 '22 at 06:09
-
+1 I love `pathlib` but had no idea I could call `rename` directly on the Path object and it would change the file! – Attila the Fun Apr 05 '23 at 16:17
import shutil
shutil.move('a.txt', 'b.kml')
This will work to rename or move a file.

- 6,423
- 6
- 34
- 37
-
44`shutil.move` is not a good option due to not being an atomic operation. If the file is open, for instance, `shutil.move` will create a file with `new_name`, but will not delete the file with `old_name` hence leaving you with two files. `os.rename` on the other hand will do nothing, which is a *better option*. With `shutil.move`, even if you caught the error, you would still have to worry about checking and deleting the rogue file. Just not worth it when **a better tool exists: `os.rename`**. – mvbentes Sep 20 '17 at 17:37
-
@mvbentes it would be interesting to know the behaviour of `pathlib` respectively `Path` with renaming open - windows - files. – Timo Feb 16 '22 at 13:32
As of Python version 3.3 and later, it is generally preferred to use os.replace
instead of os.rename
so FileExistsError
is not raised if the destination file already exists.
assert os.path.isfile('old.txt')
assert os.path.isfile('new.txt')
os.rename('old.txt', 'new.txt')
# Raises FileExistsError
os.replace('old.txt', 'new.txt')
# Does not raise exception
assert not os.path.isfile('old.txt')
assert os.path.isfile('new.txt')
See the documentation.

- 1,074
- 10
- 15
Use os.rename
. But you have to pass full path of both files to the function. If I have a file a.txt
on my desktop so I will do and also I have to give full of renamed file too.
os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')

- 14,289
- 18
- 86
- 145

- 392
- 3
- 10
-
6"Have to" isn't true. You can always substitute a relative file name for an absolute file name, and vice versa. What usually bites beginners is they don't understand how relative file names relate to the current working directory. – tripleee Oct 24 '19 at 10:21
One important point to note here, we should check if any files exists with the new filename.
suppose if b.kml file exists then renaming other file with the same filename leads to deletion of existing b.kml.
import os
if not os.path.exists('b.kml'):
os.rename('a.txt','b.kml')

- 2,654
- 2
- 18
- 24

- 866
- 1
- 9
- 25
-
1This is vulnerable to race conditions. Prefer using either `os.rename` in a `try`/`except` or `os.replace`. – bfontaine Apr 14 '22 at 07:56
import os
# Set the path
path = 'a\\b\\c'
# save current working directory
saved_cwd = os.getcwd()
# change your cwd to the directory which contains files
os.chdir(path)
os.rename('a.txt', 'b.klm')
# moving back to the directory you were in
os.chdir(saved_cwd)

- 181
- 1
- 5

- 101
- 1
- 5
-
2Be wary of doing it this way. You cannot always `chdir()` to a directory, e.g. what happens under Windows when it is a UNC? And doing a `chdir()` has side-effects. I would rather just specify the necessary paths to `os.rename()` directly, no `chdir()`ing. – JonBrave Nov 22 '18 at 09:02
-
Changing global state (the current working directory) is **not** necessary to rename files. – Sören May 02 '22 at 15:12
Using the Pathlib library's Path.rename instead of os.rename:
import pathlib
original_path = pathlib.Path('a.txt')
new_path = original_path.rename('b.kml')

- 818
- 7
- 12
-
-
1It’s just easier to use this method if all your paths are already Pathlib objects. – kym Jun 09 '21 at 02:27
-
-
Here is an example using pathlib
only without touching os
which changes the names of all files in a directory, based on a string replace
operation without using also string concatenation:
from pathlib import Path
path = Path('/talend/studio/plugins/org.talend.designer.components.bigdata_7.3.1.20200214_1052\components/tMongoDB44Connection')
for p in path.glob("tMongoDBConnection*"):
new_name = p.name.replace("tMongoDBConnection", "tMongoDB44Connection")
new_name = p.parent/new_name
p.rename(new_name)

- 12,978
- 5
- 63
- 76
How to change the first letter of filename in a directory:
import os
path = "/"
for file in os.listdir(path):
os.rename(path + file, path + file.lower().capitalize())
then = os.listdir(path)
print(then)

- 763
- 7
- 21
import shutil
import os
files = os.listdir("./pics/")
for key in range(0, len(files)):
print files[key]
shutil.move("./pics/" + files[key],"./pics/img" + str(key) + ".jpeg")
This should do it. python 3+

- 9,280
- 9
- 43
- 57

- 295
- 1
- 3
- 12
-
... or use enumerate for a slightly more readable version : for key, fname in enumerate(files): … – Nicolas D Oct 10 '18 at 09:09
-
How can you write `print files[key]` and "python 3+" in the same answer? – bfontaine Jun 30 '22 at 15:45
If you are Using Windows and you want to rename your 1000s of files in a folder then: You can use the below code. (Python3)
import os
path = os.chdir(input("Enter the path of the Your Image Folder : ")) #Here put the path of your folder where your images are stored
image_name = input("Enter your Image name : ") #Here, enter the name you want your images to have
i = 0
for file in os.listdir(path):
new_file_name = image_name+"_" + str(i) + ".jpg" #here you can change the extention of your renmamed file.
os.rename(file,new_file_name)
i = i + 1
input("Renamed all Images!!")

- 823
- 1
- 9
- 26
os.chdir(r"D:\Folder1\Folder2")
os.rename(src,dst)
#src and dst should be inside Folder2

- 837
- 11
- 9
import os
import re
from pathlib import Path
for f in os.listdir(training_data_dir2):
for file in os.listdir( training_data_dir2 + '/' + f):
oldfile= Path(training_data_dir2 + '/' + f + '/' + file)
newfile = Path(training_data_dir2 + '/' + f + '/' + file[49:])
p=oldfile
p.rename(newfile)

- 9,280
- 9
- 43
- 57

- 93
- 3
-
4Hard-coding forward slash as the path separator and mixing old-style `os.path` with modern `pathlib` is quite iffy. Go all the way with `pathlib` instead. – tripleee Oct 24 '19 at 10:23
You can use os.system to invoke terminal to accomplish the task:
os.system('mv oldfile newfile')
-
yes, this will work only on a unix-based machine as `mv` is a unix builtin commandline program to move/rename a file. – Mikhail Geyer Nov 20 '16 at 18:42
-
18Why would you invoke a terminal and define a UNIX only command when you can do it from python in a multi-platform way? – EndermanAPM Mar 29 '17 at 11:34