问题1
读取桌面文件时出现问题:SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape
错误代码:filename = “C:\Users\Ma\Desktop\test.txt”
正确代码1:filename = “C:\\Users\Ma\Desktop\test.txt”
正确代码2:filename = r"C:\Users\Ma\Desktop\test.txt"
正确代码3:filename = “C:/Users/Ma/Desktop/test.txt”
原因:
window 读取文件可以用\,但是在字符串中\是被当作转义字符来使用,所以’d:\a.txt’会被转义成’d:\a.txt’这是正确路径,所以不会报错。而‘C:\Users\FrankYuan\Pictures\Camera Roll\WIN_20161010_08_51_57_Pro.jpg ’中经过转义之后可能就找不到路径的资源了,例如\t可能就转义成tab键了。
解决办法:
python在描述路径时可以有多种方式,现列举常见的三种
方式一:转义的方式
‘d:\a.txt’
方式二:显式声明字符串不用转义
‘d:r\a.txt’
方式三:在Linux和window下都是行的通的,使用Linux的路径/
‘d:/a.txt’
问题2:UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0x94 in position 5504: illegal multibyte sequence
with open(filename) as fp:
text = fp.read()
print(text)
改为open(filename,‘rb’)即可解决字节流问题
转自:https://blog.csdn.net/u011242657/article/details/64437612
https://blog.csdn.net/zhangyunfei_happy/article/details/47169939