传递文件的内容作为python中的参数

时间:2016-08-22 05:28:36

标签: python parsing

我正在尝试根据其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()

1 个答案:

答案 0 :(得分:3)

.readlines()返回文件中的行列表。 根据一份官方文档,你也可以修改它

  

要从文件中读取行,可以循环遍历文件对象。这样可以节省内存,速度很快,并且可以实现简单的代码。

所以我猜你的代码可能会以这种方式重写

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

您可以在PEP-343页面中详细了解with关键字。

相关问题