将文件移动到碰巧在Python中具有相同文件名的新文件夹

时间:2014-06-13 01:42:53

标签: python

在我的脚本中,我很少遇到这个问题,我试图将文件移动到这个新文件夹,该文件夹已经碰巧有一个同名文件,但它只是发生了。所以我当前的代码使用shutil.move方法,但它错误的重复文件名。我希望我可以使用简单的if语句来检查源是否已经在目的地并稍微更改名称但是也无法完成该工作。我还在这里阅读了另一篇文章,其中使用了distutils模块来解决这个问题,但是这个问题给了我一个属性错误。人们对此有什么其他想法吗?

我在下面添加了一些示例代码。已有一个名为' file.txt'的文件。在' C:\ data \ new'目录。给出的错误是目标路径已存在。

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

2 个答案:

答案 0 :(得分:2)

您只需检查该文件是否存在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)

答案 1 :(得分:1)

在Python 3.4中,您可以尝试pathlib模块。这只是一个示例,因此您可以将其重写为更高效/使用变量:

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.