以下代码应该从cat.txt中获取字符串并在名为cat_results.txt的文件上打印结果
def aln_count(aln_file):
.......................
aln_file=open(aln_file,'r')
lines=aln_file.readlines()
.......................
with open(aln_file[:-4]+'_results.txt') as aln_r:
aln_results = [line.rstrip() for line in aln_r]
for seq in sequences:
for i in range(3,len(lines)-1):
if seq in lines[i]:
result.append(lines[i+1])
F=result.count('F')
aln_results.write('')
aln_results.write(seq)
aln_results.write('F: '+str(F)+' ')
aln_r.close()
result_file.close()
aln_count('cat.txt')
我得到的错误信息如下:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-f603fc5d22c0> in <module>()
32 result_file.close()
33
---> 34 aln_count('cat.txt')
<ipython-input-21-f603fc5d22c0> in aln_count(aln_file)
10 sequences.append(line[0:4])
11
---> 12 with open(aln_file[:-4]+'_results.txt') as aln_r:
13 aln_results = [line.rstrip() for line in aln_r]
14
TypeError: 'file' object has no attribute '__getitem__'
如何摆脱此错误?
答案 0 :(得分:3)
您目前在代码中覆盖aln_file
变量,以便它现在代表一个文件对象,位于aln_file=open(aln_file,'r')
行。
当您稍后尝试在with open(aln_file[:-4]+'_results.txt') as aln_r
中访问它时,您现在正在尝试切片文件对象而不是传递给该函数的原始输入,这将引发错误。
更改变量名称,应更正此错误:
aln_file_object = open(aln_file, 'r')
lines = aln_file_object.readlines()