python os.chdir 正在修改传入的目录名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17326337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:54:20  来源:igfitidea点击:

Python os.chdir is modifying the passed directory name

pythonpython-2.7directorychdir

提问by Josh Wood

I am trying to change the current working directory in python using os.chdir. I have the following code:

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

import os

os.chdir("C:\Users\Josh\Desktop130216")

However, when I run it, it seems to change the directory, as it comes out with the following error message:

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

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

Can anyone help me?

谁能帮我?

采纳答案by voithos

Python is interpreting the \2013part of the path as the escape sequence\201, which maps to the character \x81, which is ü (and of course, C:\Users\Josh\Desktopü30216doesn't exist).

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

Use a raw string, to make sure that Python doesn't try to interpret anything following a \as an escape sequence.

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

os.chdir(r"C:\Users\Josh\Desktop130216")

回答by masnun

This should work -

这应该有效 -

os.chdir("C:\Users\Josh\Desktop\20130216")

回答by vaultah

You could also use os.path.join(documentation). Example:

您也可以使用os.path.join文档)。例子:

os.chdir(os.path.join('C:\Users\Josh\Desktop', '20130216'))

This is more elegant + it's compatible with different operating systems.

这更优雅+它与不同的操作系统兼容。

回答by Ashish Patel

I have faced the same problem but you have to try:

我遇到了同样的问题,但你必须尝试:

os.chdir(c:\user\Josh\Desktop)

Use \\so maybe you should get your solution.

使用\\所以也许你应该得到你的解决方案。

回答by Anas Khan

There are two to use os.chdir():

有两个可以使用os.chdir()

  1. If you are using raw string than use single backslash \:

    os.chdir(r"C:\Users\Josh\Desktop\20130216")

  1. 如果您使用原始字符串而不是使用单个反斜杠\

    os.chdir(r"C:\Users\Josh\Desktop\20130216")

or

或者

  1. If you are not using raw string than use double backslash \\

    os.chdir("C:\Users\Josh\Desktop\20130216")

  1. 如果您不使用原始字符串,请使用双反斜杠 \\

    os.chdir("C:\Users\Josh\Desktop\20130216")