在 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 io
和 with 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/