[英]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.
因此,我当前的代码使用shutil.move方法,但是由于重复的文件名而出错。 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.
我希望我可以使用一个简单的if语句来检查源是否已在目标位置,并稍微更改名称,但也无法进行该工作。 I also read another post on here that used the distutils module for this issue but that one gives me an attribute error.
我在这里还阅读了另一篇文章,该文章使用distutils模块解决了此问题,但该帖子给了我一个属性错误。 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.
在“ C:\\ data \\ new”目录中已经有一个名为“ file.txt”的文件。 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. 您可以使用
os.path.exists
来检查文件是否存在,然后删除它(如果存在)。
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. 在Python 3.4中,您可以尝试pathlib模块。 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.