python - 使用 argparse 传递给 python 脚本的文件类型检查参数

标签 python file-type argparse

有没有办法使用 argparse 对文件名参数进行文件类型检查?如果我可以创建正确类型的容器对象,似乎可以通过 type 或 choices 关键字来完成。

我期待传入一种类型的文件(例如,file.txt)并希望 argparse 在文件不正确时给出自动消息输入 (.txt)。例如,argparse 可能输出

usage: PROG --foo filename etc... error: argument filename must be of type *.txt.

也许我们可以尝试检测文件名字符串不是以“.txt”结尾,而不是检测错误的文件类型,但这需要一个复杂的容器对象。

最佳答案

你可以使用type=关键字来指定你自己的类型转换器;如果你的文件名不正确,抛出一个ArgumentTypeError:

import argparse

def textfile(value):
    if not value.endswith('.txt'):
        raise argparse.ArgumentTypeError(
            'argument filename must be of type *.txt')
    return value

类型转换器没有来转换值..

parser.add_argument('filename', ..., type=textfile)

关于python - 使用 argparse 传递给 python 脚本的文件类型检查参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12977628/

相关文章:

Python Argparse - 如何向默认帮助消息添加文本?

python - 为什么 Scipy stdDev 返回错误的结果?

python - 尝试使用Python和BeautifulSoup来提取准确的值

asp-classic - 找出真正的文件类型

pdf - 什么是 pdf bcmap 文件?

pytorch - 错误 : unrecognized arguments: - pytorch code in colab

python - 如何将有理数或无理数提供给 argparse?

python - python项目结构是什么

python - 将实时音频数据读入 numpy 数组

javascript - Nodejs,获取文件的文件类型