2016-08-22 5 views
3

해당 ID를 기반으로 파일을 다운로드하려고합니다. IDS가 텍스트 파일에 저장되어있는 경우 어떻게 파일을 다운로드 할 수 있습니까? 여기까지 내가 한 일이파일의 내용을 파이썬에서 매개 변수로 전달하십시오.

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

관련 문제