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')

What is the best way to check if path exist and file does not exist within the dst variable..

P.S: My apologies if this is a noobish question, but the best way to learn is to make mistakes!

karthikr
  • 97,368
  • 26
  • 197
  • 188
Joseph
  • 327
  • 5
  • 17
  • Side question: Coming from C# and UNIX, where switch statements are possible, is it still good etiquette to use if statements since Python does not truly support switch-case? – Joseph Oct 21 '13 at 18:30

4 Answers4

1

os.path.exists(dst)

See the Docs

This would simply help you make sure the destination file exists or not, helping you avoid overriding an existing file. You may also need to tease out missing sub-directories along the path.

Dave
  • 2,396
  • 2
  • 22
  • 25
0
import os

if os.path.exists(dst):
    do something
emsr
  • 15,539
  • 6
  • 49
  • 62
Toni V
  • 41
  • 2
0

You can use os.path.exists(dst) as shown below:

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')
Tom Swifty
  • 2,864
  • 2
  • 16
  • 25
0

First break your destination path down into a list of folders. See the first answer here: 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

Then pass the list to this method to reassemble the list into a path and ensure that each element on the path exists or create it.

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
Community
  • 1
  • 1
Bill Kidd
  • 1,130
  • 11
  • 13