1

Can I open a gzip file directly with argparse by changing the type=argparse.FileType() to some gzip type? It's not in the docs, so I'm not sure if argparse even suppoets compressed file types...

3 Answers 3

5

First, the type parameter is a function or other callable that converts a string into something else. That's all.

argparse.FileType is factory class that ends up doing something close to:

def filetype(astring): mode = 'r' # or 'w' etc. try: f = open(astring, mode) except IOError: raise argparse.ArgumentError('') return f 

In other words, it converts the string from the commandline into an open file.

You could write an analogous type function that opens a zipped file.

FileType is just a convenience, and an example of how to write a custom type function or class. It's a convenience for small script programs that take an input file, do something, and write to an output file. It also handles '-' argument, in the same way that shell programs handle stdin/out.

The downside to the type is that it opens a file (creates if write mode), but does not provide an automatic close. You have to do that, or wait for the script to end and let the interpreter do that. And a 'default' output file will be created regardless of whether you need it or not.

So a safer method is to accept the filename, possibly with some testing, and do the open/close later with your own with context. Of course you could do that with gzip files just as well.

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

2 Comments

Got it. I didn't realize argparse doesn't close the file automatically as in the with open construct, but thinking about it makes sense
For a bug/issue I wrote a FileContext that would return an object that could be used in with context. But it took work to test for a file without actually opening or creating it, and it was tricky to handle stdin/out that way. You don't want those closed automatically. So I doubt if that patch will ever see the light of day.
4

gzip.open also accepts an open file instead of a filename, so just pass the file object opened by argparse to gzip.open to get a file-like object that reads the uncompressed data.

1 Comment

This only works if the file had been opened in "rb" mode.
0

No, argparse has no concept of file type unless you add a flag to indicate file type.

On the other hand you can use python's gzip lib with a try block to read the file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.