0

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?

Nicke7117
  • 187
  • 1
  • 10

2 Answers2

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
  • This is a really good approach . – rohith santosh Oct 22 '21 at 06:46
  • Would not pathlib be easier? – Prayson W. Daniel Oct 22 '21 at 07:25
  • @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