我想用argparse指定幾個文件擴展名。用argparse指定文件擴展名
我試過下面的代碼,但它不起作用。如何使用argparse指定多個文件擴展名?
parser.add_argument('file', action = 'store', type = argparse.FileType('r'), choices=["*.aaa", "*.bbb"])
編輯:我發現使用字符串類型,而不是文件類型的我自己的解決方案:
def input_ok(string):
if not os.path.exists(string):
raise argparse.ArgumentTypeError("Filename %r doesn\'t exists in this directory." % string)
if string[-4:] != ".aaa" and string[-4:] != ".bbb":
raise argparse.ArgumentTypeError("%r is not a .aaa or a .bbb file." % string)
return string
...
parser.add_argument('input_path', action = 'store',
type = input_ok, #argparse.FileType('r'), #choices=["*.stl", "*.csv"])
'argparse'爲您提供了一些參數驗證工具,但並不要求您使用它們。 'FileType'是一個方便的功能,用於通用腳本應用程序。如果它不適合您的應用程序,則不必使用它。 「選擇」也一樣。 – hpaulj