Python Forum
Shutil move if file exists in destination
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shutil move if file exists in destination
#1
Hi all,

i am just learning about the modul shutil and tried to move a file to a destination folder.
It works. However if i try to run the script again and overwrite the file, it doesnt work, because the file exists alreay in the destination.

shutil.move(r'C:\Users\user\Desktop\Source\t.txt', r'C:\Users\user\Desktop\Destination')
is there a way to overwrite the file if it exits ?
Reply
#2
You may have to remove the file if it exists already

if os.path.exists(r'C:\Users\user\Desktop\Source\t.txt'):
   os.remove(r'C:\Users\user\Desktop\Source\t.txt')
Reply
#3
i guess it should be like this (destination instead of source):
if os.path.exists(r'C:\Users\user\Desktop\Destination\t.txt'):
   os.remove(r'C:\Users\user\Desktop\Destination\t.txt')
hmm i thought there is some other way, without having to do this "manually"

thanks a lot
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  use of shutil.copytree with ENOTDIR exception yan 2 843 Nov-29-2023, 03:02 PM
Last Post: yan
  shutil.move make data corrupt kucingkembar 0 748 Feb-01-2023, 01:30 PM
Last Post: kucingkembar
  python move specific files from source to destination including duplicates mg24 3 1,052 Jan-21-2023, 04:21 AM
Last Post: deanhystad
  Merge htm files with shutil library (TypeError: 'module' object is not callable) Melcu54 5 1,495 Aug-28-2022, 07:11 AM
Last Post: Melcu54
  extra slashes in the network path for shutil.copy tester_V 3 3,696 Jun-02-2021, 07:57 AM
Last Post: supuflounder
  Move file from one folder to another folder with timestamp added end of file shantanu97 0 2,439 Mar-22-2021, 10:59 AM
Last Post: shantanu97
  concatenat - shutil jmabrito 3 2,146 Feb-11-2021, 12:17 PM
Last Post: jmabrito
  pathlib destpath.exists() true even file does not exist NaN 9 4,567 Dec-01-2020, 12:43 PM
Last Post: NaN
  Check if a file exists. Pedroski55 5 3,251 Sep-08-2020, 10:01 AM
Last Post: Pedroski55
  Shutil FileNotFoundError: Errno 2 Help lord_kaiser 8 10,361 Aug-10-2020, 08:45 AM
Last Post: lord_kaiser

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020