Open compressed file directly with argparse

无人久伴 提交于 2020-01-07 03:06:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!