先說下python的版本吧 3.6
1.TypeError: must be str, not bytes錯誤:
解答: 寫文件處 open(filename, 'w').write 應該寫為 open(filename, 'wb').write
2.當文本文件里面有中文時,需要進行編碼轉換,(在網上查了很多都不行)
with open("C://ch.js", encoding="utf-8") as data1:
for oneLine in data1:
print(oneLine)
編碼轉換:content = str(open(filepath).read(),'gbk').encode('utf8')
當輸出多一個b時加個decode(‘utf-8’)即可
3、對於python2中可以直接用的
如果讀取出來是字符型的 例如 tmp= b'/006ae89042325a2c7bb954a762a3d4b5.js'
在python2可以直接用,但是在3中,提示ypeError: must be str, not bytes
如果直接使用 db.name= str(tmp)。最終的結果是
db.name='b\'/006ae89042325a2c7bb954a762a3d4b5.js\''
最后的其實是 006ae89042325a2c7bb954a762a3d4b5.js‘
正確的方法是二選一
data.name = bytes.decode(tmp)
data.name = str(tmp, encoding='utf-8')
===========
附上str和bytes的轉換
hexstr、bytes、str相互轉換
h:十六進制編碼數字字符串
b:字節字符串
s: 字符串
Str to bytes:
bytes(s, encoding = “utf8”)
str.encode(s)
bytes to str:
str(b, encoding = “utf-8”)
bytes.decode(b)
hexstr to bytes
b = bytes.fromhex(h)
bytes to hexstr
h = b.hex()
str to bytes to hexstr
h = str.encode(s). hex()
hexstr to bites to str
h = bytes.decode(bytes.fromhex(h))