Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: argparse reading csv file to function

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?

like image 220
TTT Avatar asked Jun 07 '26 11:06

TTT


1 Answers

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 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'>)

and from the FileType() objects documentation:

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)

like image 130
Martijn Pieters Avatar answered Jun 10 '26 05:06

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!