在函数中以TypeError开头

use*_*873 39 python python-3.x

这是代码:

    def readFasta(filename):
        """ Reads a sequence in Fasta format """
        fp = open(filename, 'rb')
        header = ""
        seq = ""
        while True:
            line = fp.readline()
            if (line == ""):
                break
            if (line.startswith('>')):
                header = line[1:].strip()
            else:
                seq = fp.read().replace('\n','')
                seq = seq.replace('\r','')          # for windows
                break
        fp.close()
        return (header, seq)

    FASTAsequence = readFasta("MusChr01.fa")
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

TypeError: startswith first arg must be bytes or a tuple of bytes, not str
Run Code Online (Sandbox Code Playgroud)

startswith根据文档,第一个参数应该是一个字符串......那么发生了什么?

我假设我使用的是至少Python 3,因为我使用的是最新版本的LiClipse.

Ter*_*ryA 51

这是因为你以字节模式打开文件,所以你打电话bytes.startswith()而不是str.startswith().

你需要做的line.startswith(b'>'),这将使'>'一个字节的文字.