问题
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...
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/33621312/open-compressed-file-directly-with-argparse