Python如何支持读入gz压缩或未压缩文件?

Python如何支持读入gz压缩或未压缩文件?,第1张

概述目录需求示例代码笨办法Pythonic方法需求要写一个接口,同时支持压缩和未压缩文件读入示例代码笨办法importosimportgzipfilename=sys.argv[1]ifnotfilename.endswith('.gz'):withopen(filename,'r')asinfile:forlineininfile:#

目录需求示例代码笨办法Pythonic方法

需求

要写一个接口,同时支持压缩和未压缩文件读入

示例代码笨办法
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压缩或未压缩文件?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1188686.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存