2016-08-22 4 views
3

idsに基づいてファイルをダウンロードしようとしています。 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()はファイル内の行のリストを返します。 公式文書によれば、それを修正することもできます。

ファイルから行を読み込むには、ファイルオブジェクトをループすることができます。これはメモリ効率的で高速であり、簡単なコードにつながります。

だから私はあなたのコードは、あなたがPEP-343ページにwithキーワードの詳細を読むことができ、このように

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

を書き換えることが可能と思います。

+0

ありがとうございました。 –

+0

'.readlines()'は必要ありません。ファイルオブジェクトは、繰り返し時に各行を生成します。 –

+0

@friendlydog良い点!私は私の答えを編集します – vsminkov

関連する問題