Python:argparse 读取 csv 文件以发挥作用

TTT*_*TTT 2 python csv optparse python-2.7 argparse

我正在使用 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)
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:TypeError 强制转换为 Unicode:需要字符串或缓冲区,找到文件。

我怎么能解决这个问题?

Mar*_*ers 6

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

您不需要再次打开它:

def csvParser(f):
   with f:
       csv.reader(f)
Run Code Online (Sandbox Code Playgroud)

argparse文档

为了方便使用多种类型的文件中,该argparse模块提供工厂FileType这需要的mode=bufsize=encoding=errors=对的参数open()功能。例如, FileType('w') 可用于创建可写文件:

>>>
>>> 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'>)
Run Code Online (Sandbox Code Playgroud)

并从FileType()对象文档:

FileType对象作为其类型的参数将打开命令行参数作为具有请求模式、缓冲区大小、编码和错误处理的文件(open()有关更多详细信息,请参阅该函数)