2014-05-05 43 views
2

我是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)) 

什麼是使用​​在兩個文本文件的正確方法是什麼? '-h'按預期工作,但除此之外,我收到一個錯誤,說error: argument --same: expected one argument

P.S.最後,我將取代這兩個命令集與/開放

回答

3

1)定義--same--diff他們需要一個參數跟隨他們將被分配到解析參數命名的方式。爲了讓他們,而不是布爾標誌,將更改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,解析的說法實際上是一個已經打開的文件對象 - 所以d on't使用就可以了open()

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

注意:目前用戶可以合法地同時指定--same--diff,所以你的程序需要面對這一切。你可能會想製作這些標誌mutually exclusive

+1

'argparse'提供了一個'FileType'類使用代替'type'參數的'file',這有兩個好處:你可以指定文件是否打開以供讀取或寫入,並且可以使用「 - 」作爲標準輸入或標準輸出的同義詞取決於我在文件模式下)。 – chepner

+1

如果你想使用'with ... open',不要使用'FileType'。只需接受一個文件名(字符串)。對於簡單的腳本使用,「FileType」可以使用,但在文件使用更加繁瑣時會失敗。這個主題有幾個Python bug_issues。 – hpaulj

2

因爲默認add_argument()用於採用參數(嘗試--help)的參數,但您必須設置action=store_true

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

這裏是你的--help

>>> parser.parse_args(['--help']) 
usage: [-h] [--same SAME] [--diff DIFF] infile1 infile2 

Compare two lists. 

positional arguments: 
    infile1 
    infile2 

optional arguments: 
    -h, --help show this help message and exit 
    --same SAME Find those in List1 that are the same in List2 
    --diff DIFF Find those in List2 that do not exist in List2 

,一旦你的論點進行解析,您可以訪問他們作爲參數的個數成員:

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