简体   繁体   English

Python:argparse读取csv文件以起作用

[英]Python: argparse reading csv file to function

I'm using argparse and I want something like: test.py --file hello.csv 我正在使用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)

I get an error: TypeError coercing to Unicode: need string or buffer, file found. 我收到一个错误:TypeError强制转换为Unicode:需要字符串或缓冲区,找到文件。

How would I be able to fix this? 我将如何解决这个问题?

The FileType() argparse type returns an already opened fileobject. FileType() argparse类型返回已打开的文件对象。

You don't need to open it again: 您无需再次打开它:

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

From the argparse documentation : argparse文档中

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. 为了简化各种文件的使用, argparse模块提供了工厂FileType ,它使用open()函数的mode=bufsize=encoding=errors=参数。 For example, FileType('w') can be used to create a writable file: 例如,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'>) 

and from the FileType() objects documentation: 并从FileType()对象文档中:

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) 具有FileType对象作为其类型的参数将以文件的形式打开命令行参数,这些文件具有所请求的模式,缓冲区大小,编码和错误处理(有关更多详细信息,请参见open()函数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM