Home > Software engineering >  How can I overwrite a file by changing name?
How can I overwrite a file by changing name?

Time:10-23

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?

CodePudding user response:

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)

CodePudding user response:

Using pathlib is easier. It is just .rename

from pathlib import Path

nothing = Path('nothing.txt')
nothing.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())
  • Related