MetalMuzu
MetalMuzu

Reputation: 133

Python: Check folder directory given by user input

I'm creating some python code, where its initial stage lets the user input the directory of a source folder, destination folder and a text file. These directories should be checked right after the user input. Here is an example how it should look like:

Enter directory path of a source folder:
>>>C:\bla\source_folder
Thanks, this folder exists.

Enter directory path of a destination folder:
>>>C:\dest_folder            

(let's say this folder does not exist)

This folder does not exist! Please enter correct path.
>>>C:\bla\dest_folder

Enter directory path of a text file:
>>>C:\bla\bla.txt
Thanks, this file exists.

My code is incomplete, and probably wrong, because I really don't know how to do it.

def source_folder()
    source_folder = raw_input("Enter path of source folder: ")
    try:
        if open(source_folder)
            print("Folder path is correct!")
    except:
        #if there are any errors, print 'fail' for these errors
        print(source_folder, 'This folder has not been found')

def dest_folder()
    dest_folder = raw_input("Enter path of destination folder: ")

def input_file()
    input_file = raw_input("Enter path of your text file: ")

Upvotes: 0

Views: 3803

Answers (2)

MetalMuzu
MetalMuzu

Reputation: 133

Together with @massiou's advice I completed this script as follows:

import os

found = False
source_folder=None
dest_folder=None
text_file=None


while not found:
    source_folder = str(raw_input("Enter full path of source folder: "))
    print source_folder
    if not os.path.isdir(source_folder):
        print(source_folder, 'This folder has not been found. Enter correct path. ')
    else:
        print("Folder path is correct!")
        found = True

found = False
while not found:
    dest_folder = raw_input("Enter full path of destination folder: ")
    if not os.path.isdir(dest_folder):
        print(dest_folder, 'This folder has not been found. Enter correct path. ')
    else:
        print("Folder path is correct!")
        found = True

found = False
while not found:
    text_file = raw_input("Enter full path your text file folder: ")
    if not os.path.isfile(text_file):
        print(text_file, 'This file has not been found. Enter correct path. ')
    else:
        print("File path is correct!")
        found = True

Upvotes: 0

mvelay
mvelay

Reputation: 1520

try https://docs.python.org/2/library/os.path.html#os.path.isdir

 if os.path.isdir(source_folder):
     print("Folder path is correct!")

The same way for file with https://docs.python.org/2/library/os.path.html#os.path.isfile

Upvotes: 1

Related Questions