I'm using argparse and I want something like: 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.
How would I be able to fix this?
The FileType() argparse type returns an already opened fileobject.
You don't need to open it again:
def csvParser(f):
with f:
csv.reader(f)
From the argparse documentation:
To ease the use of various types of files, the
argparsemodule provides the factoryFileTypewhich 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'>)
and from the FileType() objects documentation:
Arguments that have
FileTypeobjects 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With