简体   繁体   中英

Move file to a new folder that happens to have the same file name in Python

Within in my script it's very rare that I run into this problem where I'm trying to move a file to this new folder that already happens to have a file with the same name, but it just happened. So my current code uses the shutil.move method but it errors out with the duplicate file names. I was hoping I could use a simple if statement of checking if source is already in destination and change the name slightly but can't get to that work either. I also read another post on here that used the distutils module for this issue but that one gives me an attribute error. Any other ideas people may have for this?

I added some sample code below. There is already a file called 'file.txt' in the 'C:\\data\\new' directory. The error given is Destination path already exist.

import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
shutil.move(myfile, newpath)

You can just check that the file exists with os.path.exists and then remove it if it does.

import os
import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
# if check existence of the new possible new path name.
check_existence = os.path.join(newpath, os.path.basename(myfile))
if os.path.exists(check_existence):
    os.remove(check_existence)
shutil.move(myfile, newpath)

In Python 3.4 you can try the pathlib module. This is just an example so you can rewrite this to be more efficient/use variables:

import pathlib
import shutil

myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"

p = pathlib.Path("C:\data\new")
if not p.exists():
   shutil.move(myfile, newpath)
#Use an else: here to handle your edge case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM