我想打开的文件夹叫做python,它在我的桌面上。
当我试图打开它时,出现了以下错误:
>>> os.chdir('C:\Users\expoperialed\Desktop\Python')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
您需要使用一个原始字符串,将您的斜杠加倍或使用正斜杠代替:
r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'
\U
字符组合表示扩展的Unicode代码点转义。\a
、\t
或\x
等已识别的转义序列。DeprecationWarning
(您将需要删除这些默认过滤器),并且在将来的Python版本中,这样的未识别的转义序列将导致SyntaxError
。目前还没有设置具体的版本,但是Python将首先在版本之前使用SyntaxWarning
,然后才会出现错误。
如果你想在Python 3.6及以上版本中找到这些问题,你可以通过使用警告过滤器error:^invalid escape sequence .*:DeprecationWarning
(通过命令行开关、环境变量或函数调用)将警告转换为SyntaxError
异常:
Python 3.10.0 (default, Oct 15 2021, 22:25:32) [Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import warnings
>>> '\expoperialed'
'\\expoperialed'
>>> warnings.filterwarnings('default', '^invalid escape sequence .*', DeprecationWarning)
>>> '\expoperialed'
<stdin>:1: DeprecationWarning: invalid escape sequence '\e'
'\\expoperialed'
>>> warnings.filterwarnings('error', '^invalid escape sequence .*', DeprecationWarning)
>>> '\expoperialed'
File "<stdin>", line 1
'\expoperialed'
^^^^^^^^^^^^^^^
SyntaxError: invalid escape sequence '\e'
filePath = "C:\\User\\Desktop\\myFile"
对于Python 2版本,只需使用“\”即可。
\Uxxxxxxxx
只能在Unicode字符串中使用,因此需要使用u'....'
。在Python 2字节串中,还有其他的转义序列也会触发相同的问题,例如\Users\xander
,其中\x
是十六进制转义序列的开始。 - Martijn Pietersf = open('C:\\Users\\Pooja\\Desktop\\trolldata.csv')
在Python 3及以上版本中,如果要编写Python程序,请使用'\\'。 这样可以避免出现错误。
\Uxxxxxxxx
只适用于Unicode字符串,因此需要使用u'....'
。在Python 2字节串中,还有其他转义序列也会触发相同的问题,例如\Users\xander
,其中\x
是十六进制转义序列的开始。除此之外,这个答案只是重复了我在2013年所说的话。 - Martijn Pieters所有三种语法都非常好用。
另一种方法是先写
path = r'C:\user\...................'(无论您的路径是什么)
然后将其传递给 os.chdir(path)
r'....'
是我在2013年回答中提到的三个选项之一。 - Martijn Pieters我遇到了同样的错误。 基本上,我怀疑路径不能以"C:\"后面的"U"或"User"开头。 我把我想要从Python访问的文件放在'C:\'路径下,将我的目录更改为"c:\file_name.png"。
在你的情况下,如果你必须访问"python"文件夹,也许重新安装Python,并将安装路径更改为类似于"c:\python"的东西。否则,只需避免在路径中使用"...\User...",并将你的项目放在C:下。
U
开头,没有必要重新安装任何东西。 - Martijn Pieters
s.chdir(r'C:\Users\expoperialed\Desktop\Python')
命令;阅读:http://docs.python.org/2/reference/lexical_analysis.html#string-literals - NullUserException