我正在使用 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)
To ease the use of various types of files, the
argparse
module provides the factoryFileType
which takes themode=
,bufsize=
,encoding=
anderrors=
arguments of theopen()
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 theopen()
function for more details)
关于Python:argparse 读取 csv 文件以发挥作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17370504/