简体   繁体   English

让用户选择保存文件的目录,如果目录不存在,如何再次请求目录

[英]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. 现在,如果输入的目录存在,它会破坏代码并打印目录不存在的Traceback。 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. 我不知道你的编程背景是什么 - 在找到Python之前我是SAS,而且一些结构很难思考,因为Python中的方法非常简单,没有goto或类似的声明,但我仍然在尝试添加一个goto方法,然后有人提醒我,虽然不是更简单,更容易阅读等等。

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. 我应该补充一点,你真的不需要我把它放在那里的else语句来测试/验证我的代码是否可行。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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