Python:argparse读取csv文件来实现

时间:2013-06-28 17:33:53

标签: python csv python-2.7 argparse optparse

我正在使用argparse,我想要类似的东西:test.py --file hello.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:需要字符串或缓冲区,找到文件。

我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:4)

FileType() argparse类型会返回已打开的文件对象。

您无需再次打开它:

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

来自argparse documentation

  

为了便于使用各种类型的文件,argparse模块提供工厂FileType,其中包含mode=bufsize=encoding=和{ {1}} errors=函数的参数。例如,FileType('w')可用于创建可写文件:

open()

FileType() objects文档:

  

>>> >>> 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函数)