2016-08-22 67 views
3

我试图根据它们的ID下载文件。如果我将他们的IDS存储在文本文件中,我如何下载这些文件。这是我迄今为止所做的在Python中传递文件的内容作为参数

import urllib2 

#code to read a file comes here 

uniprot_url = "http://www.uniprot.org/uniprot/" # constant Uniprot Namespace 

def get_fasta(id): 

    url_with_id = "%s%s%s" %(uniprot_url, id, ".fasta") 
    file_from_uniprot = urllib2.urlopen(url_with_id) 

    data = file_from_uniprot.read() 
    get_only_sequence = data.replace('\n', '').split('SV=')[1] 
    length_of_sequence = len(get_only_sequence[1:len(get_only_sequence)]) 
    file_output_name = "%s%s%s%s" %(id,"_", length_of_sequence, ".fasta") 


    with open(file_output_name, "wb") as fasta_file: 
     fasta_file.write(data) 
     print "completed" 

def main(): 
    # or read from a text file 
    input_file = open("positive_copy.txt").readlines() 
    get_fasta(input_file) 


if __name__ == '__main__': 
    main() 

回答

3

.readlines()返回文件中行的列表。 根据官方文档,您也可以对其进行修改

对于从文件中读取行,您可以遍历文件对象。这是有效的,快速的,并导致简单的代码。

所以我想你的代码可能会以这种方式被改写

with open("positive_copy.txt") as f: 
    for id in f: 
     get_fasta(id.strip()) 

您可以在PEP-343页面阅读更多关于with关键字。

+0

非常感谢。 –

+0

而'.readlines()'不需要。该文件对象将在迭代时产生每一行。 –

+0

@friendlydog好点!我会编辑我的答案 – vsminkov