2013-06-28 4 views
0

기능하도록 읽고 내가 좋아하는 뭔가를 원하는 argparse : 유니 코드 형식 오류의 강요 : test.py --file hello.csv파이썬 : csv 파일 내가 argparse을 사용하고

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) 

을 나는 오류가 필요 문자열을 또는 버퍼, 발견 된 파일.

어떻게이 문제를 해결할 수 있습니까?

답변

4

FileType()argparse 유형은 이 이미 열려있는 파일 객체를 반환합니다. argparse documentation에서

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

을 :

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

, 당신은 어떻게 생각하십니까 이 이미 열려있는 fileobject 걸릴 수 있고 내가 만든 함수를 통해 구문 분석 할 수있을 것이라고? 알았지 만, 사용자가 명령 프롬프트에 파일 이름을 입력 할 수있게하려고합니다. – TTT

+0

@TTT : 파일 개체는 단지 개체입니다. 그것을 함수에 전달하십시오. –

+0

@TTT : 사용자 **는 ** 파일 이름을 입력 할 수 있습니다. 'argparse'는 그 파일을 열고 당신에게 결과 파일 객체를줍니다. –

관련 문제