繁体   English   中英

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

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

在我的脚本中,很少遇到这个问题,因为我试图将文件移动到这个新文件夹中,而这个新文件夹恰好有一个具有相同名称的文件,但这只是发生了。 因此,我当前的代码使用shutil.move方法,但是由于重复的文件名而出错。 我希望我可以使用一个简单的if语句来检查源是否已在目标位置,并稍微更改名称,但也无法进行该工作。 我在这里还阅读了另一篇文章,该文章使用distutils模块解决了此问题,但该帖子给了我一个属性错误。 人们对此还有其他想法吗?

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

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

您可以使用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)

在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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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