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

まず、宛先パスをフォルダーのリストに分割します。ここで最初の回答を参照してください: How to split a path into components .

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 に答える
0
import os

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