Python 读取 .gz 文件全过程

作者:努力沉淀 时间:2021-11-02 16:01:04 

Python 读取 .gz 文件

读取.gz 文件需要使用gzip 包,如果没有安装可以自行在终端安装

pip install gzip
import gzip
path = "" #你的文件路径
f = gzip.open(path, 'rb')
 
for line in f.readlines(): # 按行进行读取
    s = line.decode() # 读取之后要进行解码
    print(s) # s 为string类型,就是我们读取的文件中的一行

也可以批量读取,批量读取文件使用os包对文件夹中的所有文件进行

import gzip
import os\
 
path = "" #表示你要打开的文件夹
files = os.listdir(path) #files 是path中存放的所有文件名集合
for file in files:
    f = gzip.open(path+file, 'rb')
    for line in f.readline():
        print(line)

Python 读取gz文件,字符串与字节串的相互转换

首先是字节串转字符串,也就是str:

b = b'some byte array'
 
str(b, encoding = "utf-8")  
#or
bytes.decode(b)

然后是字符串转为字节串:

s = 'some string'
 
bytes(s, encoding = "utf8")  
#or
str.encode(s)

fastq.gz文件读取

with gzip.open(fq,'r') as fastq:
    try:
        while True:
            line1 = next(fastq).decode()  # 字节转字符串
            line2 = next(fastq).decode()
            line3 = next(fastq).decode()
            line4 = next(fastq).decode()
            
    except:
            pass

来源:https://blog.csdn.net/qq_39129717/article/details/123380595

标签:Python,读取,gz文件
0
投稿

猜你喜欢

  • Django 使用Ajax进行前后台交互的示例讲解

    2023-08-03 03:57:47
  • 网页广告 Banner 设计图文手册

    2007-10-18 19:56:00
  • python上下文管理器协议的实现

    2023-08-28 18:32:18
  • Python实现简单猜数字游戏

    2021-03-22 14:31:50
  • 如何使用Python对Excel表格进行拼接合并

    2021-03-15 18:01:54
  • 解读python正则表达式括号问题

    2023-08-10 10:22:19
  • python numpy实现多次循环读取文件 等间隔过滤数据示例

    2022-10-30 09:44:13
  • ASP下检测图片木马的函数代码

    2011-02-05 10:43:00
  • Golang Gin局部和全局中间件使用详解

    2023-07-10 03:03:00
  • go-cache的基本使用场景示例解析

    2023-08-06 00:52:02
  • asp如何让用户也能修改密码?

    2010-05-13 16:41:00
  • php filter协议使用方法

    2023-05-29 19:36:40
  • z-index在IE中的迷惑

    2007-05-11 16:50:00
  • Access创建一个简单MIS多媒体管理系统

    2008-10-13 12:31:00
  • python中enumerate函数遍历元素用法分析

    2021-08-07 10:07:18
  • js查找父节点的简单方法

    2023-09-11 01:12:42
  • Python sklearn CountVectorizer使用详解

    2023-06-20 08:19:05
  • 有时间先后的翻页

    2008-05-23 13:14:00
  • Python可变和不可变、类的私有属性实例分析

    2023-05-27 14:34:08
  • linux下编译boost.python简单方法

    2021-01-22 15:32:44
  • asp之家 网络编程 m.aspxhome.com