2013-06-28 4 views
0

Я использую argparse и я хочу что-то вроде: test.py --file hello.csvPython: 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) 

Я получаю сообщение об ошибке: TypeError Принуждение к Unicode: нужна строке или буфер, найденный файл.

Как я могу это исправить?

ответ

4

FileType()argparse тип возвращает уже открыт 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' затем открывает этот файл для вас и дает вам полученный файл-файл. –