0
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:如果这是一个愚蠢的问题,我很抱歉,但最好的学习方法是犯错误!

4

4 回答 4

1

os.path.exists(dst)

查看文档

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

于 2013-10-21T18:22:55.333 回答
0

您可以使用 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')
于 2013-10-21T18:27:18.133 回答
0
import os

if os.path.exists(dst):
    do something
于 2013-10-21T18:22:03.623 回答
0

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

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
于 2015-02-25T14:06:45.290 回答