2013-06-28 115 views
0

我使用argparse,我想是這樣的:test.py --file hello.csv的Python:argparse閱讀CSV文件的功能

def parser(): 
    parser.add_argument("--file", type=FileType('r')) 
    options = parser.parse_args() 

    return options 

def csvParser(filename): 
    with open(filename, 'rb') as f: 
     csv.reader(f) 
     .... 
    .... 
    return par_file 

csvParser(options.filename) 

我得到一個錯誤:類型錯誤脅迫爲Unicode:需要字符串或緩衝區,找到文件。

我該如何解決這個問題?

回答

4

FileType()​​類型返回已打開 fileobject。

你不需要再次打開它:

def csvParser(f): 
    with f: 
     csv.reader(f) 

argparse documentation

To ease the use of various types of files, the argparse module provides the factory FileType which takes the mode= , bufsize= , encoding= and errors= arguments of the open() function. For example, FileType('w') can be used to create a writable file:

>>> 
>>> parser = argparse.ArgumentParser() 
>>> parser.add_argument('bar', type=argparse.FileType('w')) 
>>> parser.parse_args(['out.txt']) 
Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>) 

,並從FileType() objects文檔:

Arguments that have FileType objects as their type will open command-line arguments as files with the requested modes, buffer sizes, encodings and error handling (see the open() function for more details)

+0

那麼,你怎麼想我將能夠採取這已經打開的文件對象,並通過我創建的函數解析它?我明白了,但是我想要它,所以用戶可以在命令提示符下輸入文件名 – TTT

+0

@TTT:文件對象只是對象。將它傳遞給函數。 –

+0

@TTT:您的用戶**可以輸入文件名。 'argparse'然後爲你打開這個文件並給你生成的文件對象。 –