Python文件的读写以及解决报错io.UnsupportedOperation: not readable

编码解码知识

Python文件的读写以及解决报错io.UnsupportedOperation: not readable_第1张图片

print('肥鼠'.encode('utf-8'))
print('肥鼠'.encode('gbk'))
print(b'\xe8\x82\xa5\xe9\xbc\xa0'.decode('utf-8'))
print(b'\xb7\xca\xca\xf3'.decode('gbk'))

打印出来的是下图

b'\xe8\x82\xa5\xe9\xbc\xa0'
b'\xb7\xca\xca\xf3'
肥鼠
肥鼠

如果出现报错SyntaxError: unexpected EOF while parsing,看看我们是否少打了括号之类的

print(b'\xe6\x88\x91\xe5\x96\x9c\xe6\xac\xa2\xe4\xbd\xa0'.decode('utf-8'))
print(b'\xce\xd2\xcf\xb2\xbb\xb6\xc4\xe3'.decode('gbk'))

哈哈哈,这是程序员的一种闷骚表白方式。

我喜欢你
我喜欢你

所谓的编码,其实本质就是把str(字符串)类型的数据,利用不同的编码表,转换成bytes(字节)类型的数据。

print(type('肥鼠'))
print(type(b'\xe8\x82\xa5\xe9\xbc\xa0')) 
<class 'str'>
<class 'bytes'>

\x代表分隔符

$ python
Python 3.7.3 (default, Mar 27 2019, 22:11:17) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> open('/home/warmtree/文档/919.o

你可能感兴趣的:(#,Python,人工智能,python,列表,文件读写)