将文件移动到一个文件名相同的新文件夹中(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)
2 个回答
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.
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)