Python 从函数中的类型错误开始
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19827615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
startswith TypeError in function
提问by user2287873
Here is the code:
这是代码:
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")
The error I'm getting is:
我得到的错误是:
TypeError: startswith first arg must be bytes or a tuple of bytes, not str
But the first argument to startswith
is supposed to be a string according to the docs... so what is going on?
但是startswith
根据文档, to的第一个参数应该是一个字符串......那么发生了什么?
I'm assuming I'm using at least Python 3 since I'm using the latest version of LiClipse.
我假设我至少使用 Python 3,因为我使用的是最新版本的 LiClipse。
采纳答案by TerryA
It's because you're opening the file in bytes mode, and so you're calling bytes.startswith()
and not str.startswith()
.
这是因为您以字节模式打开文件,所以您正在调用bytes.startswith()
而不是str.startswith()
.
You need to do line.startswith(b'>')
, which will make '>'
a bytes literal.
你需要做的line.startswith(b'>')
,这将使'>'
一个字节的文字。
回答by Andre Odendaal
Without having your file to test on try encoding to utf-8 on the 'open'
无需您的文件进行测试,尝试在“打开”上将其编码为 utf-8
fp = open(filename, 'r', encoding='utf-8')
回答by wenching
If remaining to open a file in binary, replacing 'STR' to bytes('STR'.encode('utf-8')) works for me.
如果要以二进制形式打开文件,请将 'STR' 替换为 bytes('STR'.encode('utf-8')) 对我有用。