示例代码笨办法要写一个接口,同时支持压缩和未压缩文件读入
import osimport gzipfilename = sys.argv[1]if not filename.endswith('.gz'): with open(filename, 'r') as infile: for line in infile: # do somethingelse: with gzip.open(filename, 'r') as infile: for line in infile: # do something
代码一长,肯定很难看。尝试写成函数。
Pythonic方法def openfile(filename, mode='r'): if filename.endswith('.gz'): return gzip.open(filename, mode) else: return open(filename, mode)with openfile(filename, 'r') as infile: for line in infile: # do something
总结https://stackoverflow.com/questions/41525690/open-file-depending-on-whether-its-gz-or-not
以上是内存溢出为你收集整理的Python如何支持读入gz压缩或未压缩文件?全部内容,希望文章能够帮你解决Python如何支持读入gz压缩或未压缩文件?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)