【问题标题】:change current working directory in python在python中更改当前工作目录
【发布时间】:2014-01-14 18:56:58
【问题描述】:

我在桌面上创建了一个名为“headfirstpython”的文件夹,我需要将我当前的工作目录更改为该文件夹以及其中的子文件夹。我使用 os.getcwd() 来获取当前文件夹,它给了我“C\Python32”。我使用 os.chdir('../headfirstpython/chapter3') 来更改目录,但它告诉它找不到路径

>>> import os
>>> os.getcwd()
'C:\\Python32'
>>> os.chdir('../headfirstpython/chapter 3')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
os.chdir('../headfirstpython/chapter 3')
WindowsError: [Error 3] The system cannot find the path specified:         '../headfirstpython/chapter 3'
>>> os.chdir('../headfirstpython/chapter3')
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
os.chdir('../headfirstpython/chapter3')
WindowsError: [Error 3] The system cannot find the path specified:   '../headfirstpython/chapter3'
>>> 

【问题讨论】:

  • 可能是斜线类型错误 (/ instead of \\ ) 造成的?
  • “桌面”上的文件夹不在根目录下,所以相对路径不起作用。尝试例如"\\Users\\&lt;your user name&gt;\\Desktop\\the path"(或类似的,不记得确切的路径)。
  • 你能像@JoachimPileborg 所说的那样尝试吗,我认为这会奏效。
  • How do I "cd" in python的可能重复

标签: python


【解决方案1】:

我认为一些事情可能会有所帮助。

看起来您使用的是 Windows 系统,因此您应该使用双反斜杠“\\”来分隔文件夹。

其次,如果您尝试更改为当前文件夹中的文件夹,您应该使用一个点,而不是两个,例如os.chdir('.\\文件夹')

最后,如果您尝试访问的文件夹不是当前工作目录的直接子文件夹(或在您的路径中),您需要包含完整路径才能访问它。既然你说它在你的桌面上,你可能想要这样的东西:

import os
os.chdir('C:\\Users\\username\\Desktop\\headfirstpython') ## Where username is replaced with your actual username

从这里,您还可以使用以下内容将目录更改为第 3 章子目录

os.chdir('chapter3') 

在这种情况下与

等价
os.chdir('.\\chapter3')

或者,如果你想罗嗦:

os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3')

希望这有帮助吗?

【讨论】:

  • 在书中它只是告诉我创建一个文件夹而不是在哪里,所以我只是在桌面上创建了一个文件夹。但这确实可以解决问题。
【解决方案2】:

我之前也遇到过同样的问题。当我发现如果我在我的桌面上创建一个文件时,我解决了这个问题,文件图像会显示在我的桌面上,但它不会存在于 C/users/Desktop 中。也许您可以检查您的文件是否存在于您的 C 盘桌面中。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 2011-03-29
    • 2014-12-02
    • 2015-02-22
    相关资源
    最近更新 更多