我是 python 新手,目前正在尝试弄清楚如何使用 argparse 打开多个文件。从这里发布的过去的问题来看,似乎大多数人都要求只打开一个文件,我将其用作示例代码的基础。我的示例代码是:
import sys
import argparse
parser = argparse.ArgumentParser(description="Compare two lists.")
parser.add_argument('infile1', type = file)
parser.add_argument('infile2', type = file)
parser.add_argument('--same', help = 'Find those in List1 that are the same in List2')
parser.add_argument('--diff', help = 'Find those in List2 that do not exist in List2')
parser.parse_args()
data1 = set(l.rstrip() for l in open(infile1))
data2 = set(l2.rstrip() for l2 in open(infile2))
在两个文本文件上使用 argparse 的正确方法是什么? '-h' 按预期工作,但否则我会收到一条错误消息 error: argument --same: Expected one argument
。
附注最终我会将这两个 set 命令替换为 with/open
最佳答案
1) 您定义的方式 --same
和--diff
它们需要一个参数跟随它们,该参数将被分配给解析的参数 namespace 。要使它们成为 bool 标志,您可以更改 action通过指定关键字参数 action='store_true'
:
parser.add_argument('--same',
help='Find those in List1 that are the same in List2',
action='store_true')
2) 您不将解析的参数存储在变量中,并且您尝试将它们引用为局部变量,而不是 parse_args()
返回的对象。 :
args = parser.parse_args()
if args.same:
# ...
3) 如果您指定 type=file
对于参数,解析的参数实际上已经是一个打开的文件对象 - 所以不要使用 open()
关于它:
data1 = set(l.rstrip() for l in args.infile1)
注意:目前用户可以合法指定 --same
和--diff
,所以你的程序需要处理这个问题。您可能想要将这些标志设为 mutually exclusive .
关于python - 使用 argparse 打开两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23480113/