55

这是代码:

    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")

我得到的错误是:

TypeError: startswith first arg must be bytes or a tuple of bytes, not str

但是startswith根据文档,第一个参数应该是一个字符串......那是怎么回事?

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

4

3 回答 3

69

这是因为您正在以字节模式打开文件,所以您正在调用bytes.startswith()而不是str.startswith().

您需要这样做,这line.startswith(b'>')将使字节文字'>'

于 2013-11-07T03:45:07.767 回答
1

如果要以二进制文件打开文件,请将 'STR' 替换为 bytes('STR'.encode('utf-8')) 对我有用。

于 2019-07-16T14:45:34.953 回答
0

无需在“打开”时尝试将文件编码为 utf-8 进行测试

fp = open(filename, 'r', encoding='utf-8')
于 2017-01-29T17:58:49.887 回答