將讀取文件的代碼封裝成函數,並使其作為模塊可在其他程序運行
創建fasta_def.py文件,並輸入如下代碼:
1 def read_fasta(input): #用def定義函數read_fasta(),並向函數傳遞參數用變量input接收 2 with open(input,'r') as f: # 打開文件 3 fasta = {} # 定義一個空的字典 4 for line in f: 5 line = line.strip() # 去除末尾換行符 6 if line[0] == '>': 7 header = line[1:] 8 else: 9 sequence = line 10 fasta[header] = fasta.get(header,'') + sequence 11 return fasta 12 13 14 if __name__ == '__main__': # 函數若是在當前程序運行則執行下面的代碼,若是在另外的程序作為模塊運行則不執行下面的代碼 15 fasta_info = read_fasta('genome_test.fa') 16 print(fasta_info)
新建一個test.py文件
輸入如下代碼調用上述模塊fasta_def
1 import fasta_def 2 3 fa = fasta_def.read_fasta('genome_test.fa')