SyntaxError: (unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 2-3 解决办法

问题描述

import tarfile  
t=tarfile.open('C:\Users\Administrator\Desktop\20newsbydate.tar.gz', "r:gz")
t.extractall(path ='C:\Users\Administrator\Desktop')  

运行如上 解压文件的代码出错:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

在这里插入图片描述
问题原因:
在windows系统当中读取文件路径可以使用,但是在python字符串中\有转义的含义。需要采取一些方式使得\不被解读为转义字符。

解决办法:
1、在路径前面加r,即保持字符原始值的意思。

import tarfile  
t=tarfile.open(r'C:\Users\Administrator\Desktop\20newsbydate.tar.gz', "r:gz")
t.extractall(path =r'C:\Users\Administrator\Desktop')  

运行程序,解压文件。
在这里插入图片描述

2、替换为双反斜杠在这里插入图片描述

参考:https://blog.csdn.net/xd060606/article/details/87164798