Python:检查用户输入给出的文件夹目录

时间:2016-02-25 13:36:10

标签: python python-2.7 user-input

我正在创建一些python代码,其初始阶段允许用户输入源文件夹,目标文件夹和文本文件的目录。用户输入后应立即检查这些目录。下面是一个示例:

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            
  

(假设此文件夹不存在)

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.

我的代码不完整,可能错误,因为我真的不知道该怎么做。

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: ")

2 个答案:

答案 0 :(得分:1)

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

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

使用https://docs.python.org/2/library/os.path.html#os.path.isfile

的文件的方式相同

答案 1 :(得分:0)

与@ massiou的建议一起,我完成了以下脚本:

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