3

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?

1 Answer 1

8

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)

Sign up to request clarification or add additional context in comments.

4 Comments

So, how do you think I would be able to take this already opened fileobject and parse it through a function I created? I see, but I would want it so a user would be able to type the filename into the command prompt
@TTT: File objects are just objects. Pass it to the function.
@TTT: Your user is able to type in the filename. argparse then opens that file for you and gives you the resulting fileobject.
Ah! Thank you that makes perfect sense. Thank you. I will use this as the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.