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

标签 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 coercing to Unicode: need string or buffer, file found.

我该如何解决这个问题?

最佳答案

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

您不需要再次打开它:

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)

关于Python:argparse 读取 csv 文件以发挥作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17370504/

相关文章:

python - 有没有办法在 Pandas 中分类数据?

python - 为什么这个 python 正则表达式不能编译?

python - 如何检查是否分配了 Unicode 代码点?

Linux shell CSV查看器工具可以卡住标题?

python - 在Python中写入CSV

python-2.7 - 在 OpenCv (python) 中读取文件夹中的多个图像

list - 在列表中查找numpy数组的索引

python - 如何保持Python服务器连接打开,直到客户端完成它?

linux - 如何根据Linux中的条件(使用awk或其他方法)从另一个csv文件中的一个csv文件中替换行?

python - 使用 Xpath、Python 从网站提取信息