如何在一个目录中的多个文件上传递Biopython SeqIO.convert()?
我正在编写一个python脚本(版本2.7),将指定目录中的每个输入文件(.nexus格式)更改为.fasta格式。Biopython模块SeqIO.convert可以完美地处理单独指定文件的转换,但当我尝试使用os.walk在目录上自动执行转换过程时,我无法将每个输入文件的路径名正确传递给SeqIO.convert。我哪里做错了?是否需要使用os.path模块中的join()并将完整路径名传递给SeqIO.convert如何在一个目录中的多个文件上传递Biopython SeqIO.convert()?,python,biopython,os.walk,Python,Biopython,Os.walk,我正在编写一个python脚本(版本2.7),将指定目录中的每个输入文件(.nexus格式)更改为.fasta格式。Biopython模块SeqIO.convert可以完美地处理单独指定文件的转换,但当我尝试使用os.walk在目录上自动执行转换过程时,我无法将每个输入文件的路径名正确传递给SeqIO.convert。我哪里做错了?是否需要使用os.path模块中的join()并将完整路径名传递给SeqIO.convert #Import modules import sys
#Import modules
import sys
import re
import os
import fileinput
from Bio import SeqIO
#Specify directory of interest
PSGDirectory = "/Users/InputDirectory”
#Create a class that will run the SeqIO.convert function repeatedly
def process(filename):
count = SeqIO.convert("files", "nexus", "files.fa", "fasta", alphabet= IUPAC.ambiguous_dna)
#Make sure os.walk works correctly
for path, dirs, files in os.walk(PSGDirectory):
print path
print dirs
print files
#Now recursively do the count command on each file inside PSGDirectory
for files in os.walk(PSGDirectory):
print("Converted %i records" % count)
process(files)
运行脚本时,我收到以下错误消息:
回溯(最近一次呼叫最后一次):
文件“nexus_to_fasta.psg”,第45行,在
打印(“已转换的%i条记录”%count)
名称错误:未定义名称“计数”
非常有用,但我不知道在哪里插入join()函数语句。
谢谢你的帮助 发生了一些事情 首先,进程函数没有返回“count”。您可能想要:
def process(filename):
return seqIO.convert("files", "nexus", "files.fa", "fasta", alphabet=IUPAC.ambiguous_dna)
# assuming seqIO.convert actually returns the number you want
另外,当您在os.walk(PSGDirectory)中为文件编写时,您操作的是os.walk返回的三元组,而不是单个文件。您希望执行以下操作(注意os.path.join的使用):
更新:
因此,我查看了seqIO.convert的文档,并希望通过以下方式调用它:
- in_文件-输入句柄或文件名
- in_格式-输入文件格式,小写字符串
- 输出文件-输出句柄或文件名
- 输出格式-输出文件格式,小写字符串
- 字母表-要假定的可选字母表
in_file是要转换的文件的名称,最初您只是用“files”调用seqIO.convert
因此,您的流程函数应该是这样的:
def process(filename):
return seqIO.convert(filename, "nexus", filename + '.fa', "fasta", alphabet=IUPAC.ambiguous_dna)
顺便说一句,如果seqIO没有返回任何东西(它可能只是转换一个文件),您可以只写进程(完整路径),同时知道len(文件)会告诉您处理了多少文件。这非常有帮助!但我仍然会遇到这个错误:Traceback(最近一次调用最后一次):文件“nexus_to_fasta.psg”,第41行,打印过程中(完整路径)文件“nexus_to_fasta.psg”,第35行,过程中返回SeqIO.convert(“files”,“nexus”,“files.fa”,“fasta”,alphabet=IUPAC.dna)文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site packages/Bio/sekio/uu init_uu.py”,第899行,在convert in_handle=open(in_file,“rU”)IOError:[Errno 2]没有这样的文件或目录:“files”
这个错误来自于调用convert的方式;我在查看了sekio.convert的文档后更新了答案。
def process(filename):
return seqIO.convert(filename, "nexus", filename + '.fa', "fasta", alphabet=IUPAC.ambiguous_dna)