繁体   English   中英

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

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

我正在编写一个脚本来保存文件,并提供保存此文件的位置选项。 现在,如果输入的目录存在,它会破坏代码并打印目录不存在的Traceback。 而不是破坏代码,我希望有一个解决方案告诉用户他们选择的目录不存在,并再次询问保存文件的位置。 我不想让这个脚本创建一个新目录。 这是我的代码:

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

这将让你开始但是我会注意到我认为你需要调整输入语句,这样用户就不必输入引号来获得无效的语法错误

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'

我不知道你的编程背景是什么 - 在找到Python之前我是SAS,而且一些结构很难思考,因为Python中的方法非常简单,没有goto或类似的声明,但我仍然在尝试添加一个goto方法,然后有人提醒我,虽然不是更简单,更容易阅读等等。

祝好运

我应该补充一点,你真的不需要我把它放在那里的else语句来测试/验证我的代码是否可行。 如果你希望经常这样做,那么你应该把它放在一个函数中

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