首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有关以特定格式读取.bed文件和压缩输出的问题

有关以特定格式读取.bed文件和压缩输出的问题
EN

Stack Overflow用户
提问于 2020-09-16 05:47:42
回答 1查看 69关注 0票数 0
代码语言:javascript
复制
import os #handles the gzipped output like the example file
file_name = "exampleziptotxt.bed"
out_file_root = "example_by_chrom"
file_handle_dict = {}

file_reader=open(file_name)

for line in file_reader:
    ff=line.strip().split(",")
    chrom_name=ff[0]
    if not (chrom_name in file_handle_dict):
        out_file_chrom_name=out_file_root+"."+chrom_name+".bed"
        out_file_chrom_name_handle=open(out_file_chrom_name,"w")
        file_handle_dict[chrom_name]=out_file_chrom_name_handle
    # write the line in the appropriate output file
    file_handle_dict[chrom_name].write(line)
    # file_handle_dict[chrom_name].write("%s\n"%"\t".join(ff))

file_reader.close()

# now close all open files
for chrom_name in file_handle_dict:
    file_handle_dict[chrom_name].close()

我想重写上面的代码,这样输出就是多个使用gzip或替代的gzip压缩文件。我不确定如何做到这一点。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-16 10:02:45

只需要做几处小改动,import gzip (不需要os),将.gz添加到名称中,使用gzip.open而不是open进行写入,并在行上使用.encode()将其转换为字节。

代码语言:javascript
复制
import gzip

file_name = "exampleziptotxt.bed"
out_file_root = "example_by_chrom"
file_handle_dict = {}

file_reader=open(file_name)

for line in file_reader:
    ff=line.strip().split(",")
    chrom_name=ff[0]
    if not (chrom_name in file_handle_dict):
        out_file_chrom_name=out_file_root+"."+chrom_name+".bed.gz"
        out_file_chrom_name_handle=gzip.open(out_file_chrom_name,"w")
        file_handle_dict[chrom_name]=out_file_chrom_name_handle
    # write the line in the appropriate output file
    file_handle_dict[chrom_name].write(line.encode())
    # file_handle_dict[chrom_name].write("%s\n"%"\t".join(ff))

file_reader.close()

# now close all open files
for chrom_name in file_handle_dict:
    file_handle_dict[chrom_name].close()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63910290

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档