python - 逐行读取 gzipped 文本文件以在 python 3.2.6 中进行处理

标签 python gzip python-3.2

在 python 方面,我是一个完全的新手,但我的任务是尝试让一段代码在具有与代码不同版本的 python (3.2.6) 的机器上运行最初是为.

我遇到了逐行读取 gzip 文本文件(并根据第一个字符处理它)的问题。代码(显然是用 python > 3.2.6 编写的)是

for line in gzip.open(input[0], 'rt'):
    if line[:1] != '>':
        out.write(line)
        continue

    chromname = match2chrom(line[1:-1])
    seqname = line[1:].split()[0]

    print('>{}'.format(chromname), file=out)
    print('{}\t{}'.format(seqname, chromname), file=mappingout)

(对于那些知道的人,这会将 gzip 压缩的 FASTA 基因组文件剥离成标题(以“>”开头)和序列,并根据此将行处理成两个不同的文件)

我找到了 https://bugs.python.org/issue13989 ,其中指出模式 'rt' 不能用于 python-3.2 中的 gzip.open 并且不能使用以下内容:

import io

with io.TextIOWrapper(gzip.open(input[0], "r")) as fin:
     for line in fin:
         if line[:1] != '>':
             out.write(line)
             continue

         chromname = match2chrom(line[1:-1])
         seqname = line[1:].split()[0]

         print('>{}'.format(chromname), file=out)
         print('{}\t{}'.format(seqname, chromname), file=mappingout)

但是上面的代码不起作用:

UnsupportedOperation in line <4> of /path/to/python_file.py:
read1

我如何重写此例程以准确给出我想要的 - 将 gzip 文件逐行读入变量“line”并根据第一个字符进行处理?

编辑:此例程的第一个版本的回溯是(python 3.2.6):

Mode rt not supported  
File "/path/to/python_file.py", line 79, in __process_genome_sequences  
File "/opt/python-3.2.6/lib/python3.2/gzip.py", line 46, in open  
File "/opt/python-3.2.6/lib/python3.2/gzip.py", line 157, in __init__

第二个版本的回溯是:

UnsupportedOperation in line 81 of /path/to/python_file.py:
read1
File "/path/to/python_file.py", line 81, in __process_genome_sequences

没有进一步的回溯(行数中的额外两行是 import iowith io.TextIOWrapper(gzip.open(input[0], "r"))作为 fin:

最佳答案

我实际上已经解决了这个问题。

最后我不得不使用 shell("gunzip {input[0]}") 来确保 gunzipped 文件可以文本模式读取,然后读取结果文件使用

for line in open(' *< resulting file >* ','r'):
    if line[:1] != '>':
        out.write(line)
        continue

    chromname = match2chrom(line[1:-1])
    seqname = line[1:].split()[0]

    print('>{}'.format(chromname), file=out)
    print('{}\t{}'.format(seqname, chromname), file=mappingout)  

关于python - 逐行读取 gzipped 文本文件以在 python 3.2.6 中进行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33285180/

相关文章:

python - Pandas dataframe - 将列值转换为单独的列

python - 使用 SQLAlchemy 的 PostgreSQL ILIKE 查询

python - 尝试在 python 子进程中运行 rsync 时出现意外的远程参数错误

php - gzopen 是否将整个文件读入内存?

http - 低流量网站上的 HTTP 压缩(GZip 或 deflate)真的有用吗?

python - 为什么返回 `None` 而不是 tkinter.Entry 对象?

python - CPython 内部结构

linux - gzip: stdin: 不是 gzip 格式 tar: Child returned status 1 tar: Error is not recoverable: exiting now

python - 函数包装装饰器的 "Bootstrap issues"是什么?

Python3.2 : Installing MySQL-python fails with error "No module named ConfigParser"