I have something.txt
and nothing.txt
. How can I change the name of nothing.txt
to something.txt
and at the same time remove the old something.txt
?
Asked
Active
Viewed 499 times
0

Nicke7117
- 187
- 1
- 10
-
1https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python – Алексей Р Oct 22 '21 at 06:34
-
Yes, but then I get this error: `PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'nothing.txt' -> 'something.txt'`. @АлексейР – Nicke7117 Oct 22 '21 at 06:35
-
use `os.replace()` https://stackoverflow.com/a/8858026/15035314 – Алексей Р Oct 22 '21 at 06:38
-
check if file is closed or not – rohith santosh Oct 22 '21 at 06:38
-
1This might help : https://stackoverflow.com/a/61541907/7734112 Regarding the PermissionError -> make sure the txt file that you are trying to modify is not in use i.e exit/close the txt file. – f__society Oct 22 '21 at 06:40
2 Answers
1
You can check if the file exist. And if it does, remove it first.
from os import path, rename, remove
def mv(source, destination, overwrite=True):
if path.isfile(destination):
if overwrite:
remove(destination)
else:
raise IOError("Destination file already exist")
rename(source, destination)

MSH
- 1,743
- 2
- 14
- 22
-
-
-
@PraysonW.Daniel I am pretty sure `pathlib` does better then what I wrote. But is it easier? Not sure. You just add another module. Especially if OP wants to use it just for this example. In my opinion it's not worth it. – MSH Oct 27 '21 at 21:49
-
Given that they are both standard libraries and `pathlib` was introduced to remove the boiler plates of `os`, I will say using Pathlib when dealing with folders and file is way to go. A one linear `Path('nothing.txt').rename('something.txt')` solves the issue. – Prayson W. Daniel Oct 28 '21 at 04:21
0
Using pathlib
is easier. It is just .rename
from pathlib import Path
Path('nothing.txt').rename('something.txt')
Demo Script
from pathlib import Path
# create file and populate with text for demo
with Path('something.txt').open('w') as f:
f.write('something old!')
# check contents
print(Path('something.txt').open('r').readline())
nothing = Path('nothing.txt')
with nothing.open('w') as f:
f.write('something new!')
# rename replaces the old something with new
nothing.rename('something.txt')
# check results
print(Path('something.txt').open('r').readline())

Prayson W. Daniel
- 14,191
- 4
- 51
- 57