Python os.chdir正在修改传递的目录名称

Jos*_*ood 10 python directory chdir python-2.7

我试图使用os.chdir更改python中的当前工作目录.我有以下代码:

import os

os.chdir("C:\Users\Josh\Desktop\20130216")
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,似乎更改了目录,因为它出现以下错误消息:

Traceback (most recent call last):
File "C:\Users\Josh\Desktop\LapseBot 1.0\LapseBot.py", line 3, in <module>
os.chdir("C:\Users\Josh\Desktop\20130216")
WindowsError: [Error 2] The system cannot find the file specified
  'C:\\Users\\Josh\\Desktop\x8130216'
Run Code Online (Sandbox Code Playgroud)

谁能帮我?

voi*_*hos 25

Python \2013将路径的一部分解释为转义序列 \201,它映射到字符\x81,即ü(当然,C:\Users\Josh\Desktopü30216不存在).

使用原始字符串,以确保Python不会尝试解释\作为转义序列之后的任何内容.

os.chdir(r"C:\Users\Josh\Desktop\20130216")
Run Code Online (Sandbox Code Playgroud)

  • 或者使用正斜杠,或者使用反斜杠加倍. (6认同)