如何检查PYthon中是否存在"dst"路径


elif user == str(3):
    src = input("Enter the location of the file you wish to copy: ")
    print('n')
    dst = input("Next, enter the location where you wish to copy the file to: ")
    if os.path.isfile(src):
        while count < 1:
            shutil.copyfile(src, dst)
            print('Copy successful')
            count = count + 1
    else:
            print('One of your paths is invalid')

检查 dst 变量中是否存在路径和文件不存在的最佳方法是什么..

PS:如果这是一个菜鸟问题,我很抱歉,但最好的学习方法是犯错误!

os.path.exists(dst)

查看文档

这只会帮助您确保目标文件是否存在,从而帮助您避免覆盖现有文件。您可能还需要梳理出路径中缺少的子目录。

您可以使用 os.path.exists(dst),如下所示:

import os
# ...
elif user == str(3):
    src = input("Enter the location of the file you wish to copy: ")
    print('n')
    dst = input("Next, enter the location where you wish to copy the file to: ")
    if os.path.isfile(src) and os.path.exists(dst):
        while count < 1:
            shutil.copyfile(src, dst)
            print('Copy successful')
            count = count + 1
    else:
            print('One of your paths is invalid')
import os
if os.path.exists(dst):
    do something

首先将目标路径分解为文件夹列表。请参阅此处的第一个答案:如何将路径拆分为组件。

from os import path, mkdir
def splitPathToList(thePath)
    theDrive, dirPath = path.splitdrive(thePath)
    pathList= list()
    while True:
        dirPath, folder = path.split(dirPath)
        if (folder != ""):
            pathList.append(folder)
        else:
            if (path != ""):
                pathList.append(dirPath)
            break
    pathList.append(theDrive)
    pathList.reverse()
    return pathList

然后将列表传递给此方法,以将列表重新组合为路径,并确保路径上的每个元素都存在或创建它。

from os import path, mkdir
def verifyOrCreateFolder(pathList): 
    dirPath  = ''
    for folder in pathList:
        dirPath = path.normpath(path.join(dirPath,folder))
        if (not path.isdir(dirPath)):
            mkdir(dirPath)
    return dirPath

最新更新