Search code examples
pythoncsvpython-2.7argparseoptparse

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?


Solution

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