-2

I want to move and overwrite file to another folder which has the same file:

d_folder = shutil.move(min_file, d_folder)
print("File is moved successfully to: ", d_folder)

Shutil move does not overwrite the file. Is there another way to move and overwrite the file?

shutil.Error: Destination path 'C:\\g.txt' already exists
pigeonburger
  • 715
  • 7
  • 24
Kaung Sat
  • 33
  • 6
  • Does this answer your question? [How to move a file in Python?](https://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python) – JE_Muc Sep 02 '21 at 13:51
  • See also: [Python - Move and overwrite files and folders - Stack Overflow](https://stackoverflow.com/questions/7419665/python-move-and-overwrite-files-and-folders) – user202729 Mar 30 '23 at 00:41

1 Answers1

1

You can't do it in a single line, you'll have to do:

import os, shutil

if os.path.isfile(os.path.join(d_folder, min_file)):
    os.remove(os.path.join(d_folder, min_file))

d_folder = shutil.move(min_file, d_folder)
print("File is moved successfully to: ", d_folder)

This checks if the file already exists, and deletes it if so, then moves the new file to there.

pigeonburger
  • 715
  • 7
  • 24