Python:类型为'_io.TextIOWrapper';没有len()

Python:类型为'_io.TextIOWrapper';没有len(),python,string,function,loops,Python,String,Function,Loops,我在运行代码时不断遇到错误: TypeError:类型为“\u io.TextIOWrapper”的对象没有len()函数 如何让它打开/读取文件并在循环中运行 以下是指向我尝试导入的文件的链接: def mostCommonSubstring(): dna=open(“dna.txt”、“r”) 貂=4 maxk=9 计数=0 检查=0 答案=”“ k=水貂 当k=检查时: 答案=sub 检查=计数 k=k+1 打印(答案) 打印(支票) 问题是由于您打开文本文件的方式造成的。 您应该在代码

我在运行代码时不断遇到错误:

TypeError:类型为“\u io.TextIOWrapper”的对象没有len()函数

如何让它打开/读取文件并在循环中运行

以下是指向我尝试导入的文件的链接:

def mostCommonSubstring():
dna=open(“dna.txt”、“r”)
貂=4
maxk=9
计数=0
检查=0
答案=”“
k=水貂
当k=检查时:
答案=sub
检查=计数
k=k+1
打印(答案)
打印(支票)

问题是由于您打开文本文件的方式造成的。 您应该在代码中添加
dna=dna.read()
。 因此,您的最终代码应该如下所示:

def mostCommonSubstring():
    dna = open("dna.txt", "r")
    dna = dna.read()
    mink = 4
    maxk = 9
    count = 0
    check = 0
    answer = ""
    k = mink
    while k <= maxk:
        for i in range(len(dna)-k+1):
            sub = dna[i:i+k]
            count = 0
            for i in range(len(dna)-k+1):
                if dna[i:i+k] == sub:
                    count = count + 1
            if count >= check:
                answer = sub
                check = count
        k=k+1
    print(answer)
    print(check)
def mostCommonSubstring():
dna=open(“dna.txt”、“r”)
dna=dna.read()
貂=4
maxk=9
计数=0
检查=0
答案=”“
k=水貂
当k=检查时:
答案=sub
检查=计数
k=k+1
打印(答案)
打印(支票)
:我建议这个脚本读取并处理DNA序列。 要运行此代码,请在终端:python readfasta.py fastafile.fasta

import string, sys
##########I. To Load Fasta File##############
file = open(sys.argv[1]) 
rfile = file.readline()
seqs = {} 
##########II. To Make fasta dictionary####
tnv = ""#temporal name value
while rfile != "":
    if ">" in rfile:
        tnv = string.strip(rfile)
        seqs[tnv] = ""
    else:
        seqs[tnv] += string.strip(rfile)    
    rfile = file.readline()
##############III. To Make Counts########
count_what = ["A", "T", "C", "G", "ATG"]
for s in seqs:
    name = s
    seq = seqs[s]
    print s # to print seq name if you have a multifasta file
    for cw in count_what:
        print cw, seq.count(cw)# to print counts by seq

您不能调用
len(dna)
文件对象没有
len
。它们也不能被切片/索引,即
dna[i:i+k]
也会失败
import string, sys
##########I. To Load Fasta File##############
file = open(sys.argv[1]) 
rfile = file.readline()
seqs = {} 
##########II. To Make fasta dictionary####
tnv = ""#temporal name value
while rfile != "":
    if ">" in rfile:
        tnv = string.strip(rfile)
        seqs[tnv] = ""
    else:
        seqs[tnv] += string.strip(rfile)    
    rfile = file.readline()
##############III. To Make Counts########
count_what = ["A", "T", "C", "G", "ATG"]
for s in seqs:
    name = s
    seq = seqs[s]
    print s # to print seq name if you have a multifasta file
    for cw in count_what:
        print cw, seq.count(cw)# to print counts by seq