python - 连接多个 .fasta 文件

标签 python concatenation fasta

我正在尝试将数百个 .fasta 文件连接成一个包含所有序列的大型 fasta 文件。我还没有在论坛中找到实现此目的的具体方法。我确实从 http://zientzilaria.heroku.com/blog/2007/10/29/merging-single-or-multiple-sequence-fasta-files 中看到了这段代码,我对此进行了一些调整。

Fasta.py 包含以下代码:

class fasta:
    def __init__(self, name, sequence):
        self.name = name
        self.sequence = sequence

def read_fasta(file):
    items = []
    index = 0
    for line in file:
        if line.startswith(">"):
           if index >= 1:
               items.append(aninstance)
           index+=1
           name = line[:-1]
           seq = ''
           aninstance = fasta(name, seq)
        else:
           seq += line[:-1]
           aninstance = fasta(name, seq)

    items.append(aninstance)
    return items

这里是连接 .fasta 文件的改编脚本:

import sys
import glob
import fasta

#obtain directory containing single fasta files for query
filepattern = input('Filename pattern to match: ')

#obtain output directory
outfile = input('Filename of output file: ')

#create new output file
output = open(outfile, 'w')

#initialize lists
names = []
seqs = []

#glob.glob returns a list of files that match the pattern
for file in glob.glob(filepattern):

    print ("file: " + file)

    #we read the contents and an instance of the class is returned
    contents = fasta.read_fasta(open(file).readlines())

    #a file can contain more than one sequence so we read them in a loop
    for item in contents:
        names.append(item.name)
        seqs.append(item.sequence)

#we print the output
for i in range(len(names)):
    output.write(names[i] + '\n' + seqs[i] + '\n\n')

output.close()
print("done")

它能够读取 fasta 文件,但新创建的输出文件不包含序列。我收到的错误是由于 fasta.py,这超出了我的处理能力:

Traceback (most recent call last):
  File "C:\Python32\myfiles\test\3\Fasta_Concatenate.py", line 28, in <module>
    contents = fasta.read_fasta(open(file).readlines())
  File "C:\Python32\lib\fasta.py", line 18, in read_fasta
    seq += line[:-1]
UnboundLocalError: local variable 'seq' referenced before assignment

有什么建议吗?谢谢!

最佳答案

我认为使用 python 来完成这项工作有点矫枉过正。在命令行上,使用 .fasta.fa 扩展名连接单个/多个 fasta 文件的快速方法是:

cat *.fa* > newfile.txt

关于python - 连接多个 .fasta 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11726340/

相关文章:

Python 包含子目录中的 Scrapy

python - cv2 和 BGR2YCrCb 不适用于 Python 绑定(bind)

python - Sklearn 使用自然语言处理数值数据

javascript - 发现 IP 八位字节,然后将其设为 href URL?

python - 多处理进程在 PyCharm 中永远锁定

php - 更新连接和变量

php - 如何在准备好的语句中使用 sql 函数 CONCAT

Python:如何根据位置输出FASTA头或染色体索引图?

python - Biopython 从变量而不是文件解析

awk - 在 fasta 文件中使用 AWK 之前删除模式和所有内容