简体   繁体   中英

Letting user choose a directory to save a file, if directory doesn't exist how to ask for a directory again

I'm writing a script to save a file and giving the option of where to save this file. Now if the directory entered does NOT exist, it breaks the code and prints the Traceback that the directory does not exist. Instead of breaking the code I'd love to have have a solution to tell the user the directory they chose does not exist and ask again where to save the file. I do not want to have this script make a new directory. Here is my code:

myDir = input('Where do you want to write the file?')
myPath = os.path.join(myDir, 'foobar.txt')
try:
    f = open(myPath, 'w')
except not os.path.exists(myDir):
    print ('That directory or file does not exist, please try again.')
    myPath = os.path.join(myDir, 'foobar.txt')
f.seek(0)
f.write(data)
f.close()

This will get you started however I will note that I think you need to tweak the input statement so the user does not have to put quotes in to not get an invalid syntax error

import os
myDir = input("Where do you want to write the file ")

while not os.path.exists(myDir):
    print 'invalid path'
    myDir = input("Where do you want to write the file ")
else:
    print 'hello'

I do not know what your programming background is - mine was SAS before I found Python and some of the constructions are just hard to think through because the approach in Python is so much simpler without having a goto or similar statement but I am still trying to add a goto approach and then someone reminds me about how the while and while not are simpler, easier to read etc.

Good luck

I should add that you really don't need the else statement I put it there to test/verify that my code would work. If you expect to do something like this often then you should put it in a function

def verify_path(some_path_string):
    while not os.path.exists(some_path_string):
        print 'some warning message'
        some_path_string = input('Prompt to get path')
    return some_path_string



if _name_ == main:
some_path_string = input("Prompt to get path")
some_path_string = verify_path(some_path_string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM