python3错误:SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3

python3错误:SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

	使用open()打开一个文件遭遇上述错误
f = open('C:\Users\joy\Desktop\资料.txt',encoding='utf-8')

SyntaxError表示语法错误,翻译如下:

	语法错误:( unicode错误)'unicodeescape'编解码器无法解码位置2-3中的字节:截断\ UXXXXXXXX转义

查看open()文件帮助如下:
	def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
"""
Open file and return a stream.  Raise IOError upon failure.

file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)

打开文件并返回一个stream。 失败时引发IOError。
file是文本或字节字符串,给出文件名称或路径(如果文件不在当前工作目录中)
来打开该文件或者一个要包装的文件的整数文件描述符。 (如果给出了文件描述符,则在关闭返回的I / O对象时将关闭它,除非将closefd设置为False。)

 以前直接用文件名打开时没问题,说明不是因为包含了中文字符,后来上网查了下发现原来是\被当做转义字符了
 解决方法:
1、 在\前面再加一个\进行转义
f = open('C:\\Users\\joy\\Desktop\\资料.txt',encoding='utf-8')
2、在字符串前面加r,表示原始字符
f = open(r'C:\Users\joy\Desktop\资料.txt',encoding='utf-8')

你可能感兴趣的:(python笔记)