Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何向脚本中添加各种选项_Python - Fatal编程技术网

Python 如何向脚本中添加各种选项

Python 如何向脚本中添加各种选项,python,Python,我对Python非常陌生。在下面的脚本中,如何向要获取的文件添加更多选项。比如说,我不确定文件是如何调用的。我选择的文件名是:“Unicorn 1.pdf”、“Unicorn 2.pdf”和“Apple 1.pdf” 我想我需要在if file.endswith(“Unicorn 1.pdf”):之后添加一个else,对吗 请帮帮我,我不知道该怎么办 请注意,我不确定文件是如何调用的,如果第一个文件名不正确,我想为文件名提供更多选项。使用argparse: import argparse par

我对Python非常陌生。在下面的脚本中,如何向要获取的文件添加更多选项。比如说,我不确定文件是如何调用的。我选择的文件名是:“Unicorn 1.pdf”、“Unicorn 2.pdf”和“Apple 1.pdf”

我想我需要在if file.endswith(“Unicorn 1.pdf”):之后添加一个else,对吗

请帮帮我,我不知道该怎么办

请注意,我不确定文件是如何调用的,如果第一个文件名不正确,我想为文件名提供更多选项。

使用argparse:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--path', default='Unicorn 1.pdf')
args = parser.parse_args()
print(args.path)
# "Unicorn 1.pdf" or whatever you give to your program as input
从终端运行:

python your_program.py --path file.pdf
请注意,如果文件名包含空格,则必须使用引号

然后,检查默认文件名是否存在,并相应地继续

import os
if os.path.exists(args.path):
    # do something with the file
else:
    # do something else, e.g. open another PDF with os.
    files = [f for f in os.listdir('.') if os.path.isfile(f)]
    for f in files:
        if f.endswith('.pdf'):
             # do something, either with ALL or just ONE (using break) of the pdfs
file.endswith(“Unicorn 1.pdf”)
表示查找名称以“Unicorn 1.pdf”结尾的文件 因此,您可以仅使用扩展来执行相同的操作:

file.endswith(“.pdf”)


如果您愿意,也可以使用

请不要让我们猜测这些“选项”是如何使用的“应该向用户展示自己——确定您正试图实现的行为,包括是否要添加命令行参数、提示或其他任何内容,并查找现有的重复项,描述如何执行该操作,描述您如何尝试应用他们的答案,以及在执行过程中出现的错误(或者如何/为什么他们没有帮助,否则)。请不要为重复的问题添加更多答案——如果这显然是OP想要的,那么这可以作为众多“如何在Python中使用命令行选项?”问题中的一个来解决,这些问题描述了如何使用argparse。(我不认为OP想要什么实际上是如此明确,以至于可以肯定它们意味着一个命令行选项,所以我自己会以不清楚或太宽泛而不是重复的方式来结束这个问题)。在中,请参阅“回答问题”一节,特别是其中的第一个和第三个要点。@CharlesDuffy好吧,如果问题不清楚并且已经回答了很多次,我很抱歉。我对该语言和该平台不熟悉,我只想知道如何继续我的脚本。
python your_program.py --path "Unicorn 1.pdf"
import os
if os.path.exists(args.path):
    # do something with the file
else:
    # do something else, e.g. open another PDF with os.
    files = [f for f in os.listdir('.') if os.path.isfile(f)]
    for f in files:
        if f.endswith('.pdf'):
             # do something, either with ALL or just ONE (using break) of the pdfs