Python如何支持讀入gz壓縮或未壓縮文件?


需求

要寫一個接口,同時支持壓縮和未壓縮文件讀入

示例代碼

笨辦法

import os
import gzip

filename = sys.argv[1]
if not filename.endswith('.gz'):
    with open(filename, 'r') as infile:
        for line in infile:
            # do something
else:
    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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM