使用argpar打开两个文件

2024-03-29 11:36:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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命令替换为/open


Tags: 文件代码inimportaddparser示例type
2条回答

1)您定义 same diff的方式要求后面有一个参数,该参数将分配给解析的参数名称空间。要使它们成为布尔标志,可以通过指定关键字参数action='store_true'来更改action

parser.add_argument(' same',
                    help='Find those in List1 that are the same in List2',
                    action='store_true')

2)您不将已解析的参数存储在变量中,而是尝试将它们作为局部变量引用,而不是在parse_args()返回的对象上:

^{pr2}$

3)如果为参数指定^{},则解析后的参数实际上已经是一个打开的文件对象,因此不要在其上使用open()

data1 = set(l.rstrip() for l in args.infile1)

注意:当前用户可以合法地同时指定 same和{},因此您的程序需要处理这一点。您可能希望将这些标志mutually exclusive。在

因为默认情况下^{}用于接受参数的参数(请尝试 help),但必须设置^{}。在

parser.add_argument(' same', help = 'Find those in List1 that are the same in List2', action='store_true')

这是您的 help

^{pr2}$

一旦参数被解析,就可以作为arg的成员访问它们:

data1 = set(l.rstrip() for l in open(args.infile1))
data2 = set(l2.rstrip() for l2 in open(args.infile2))

相关问题 更多 >