简体   繁体   English

在python中更改当前工作目录

[英]change current working directory in python

I made a folder on my desktop with the name "headfirstpython" and I need to change my current working directory to that folder and to the sub folder inside of it. 我在桌面上创建了一个名为“headfirstpython”的文件夹,我需要将当前的工作目录更改为该文件夹及其内部的子文件夹。 I used os.getcwd() to get the current folder and it gives me 'C\\Python32'. 我使用os.getcwd()获取当前文件夹,它给了我'C \\ Python32'。 I used os.chdir('../headfirstpython/chapter3') to change the directory but its telling it cannot find the path 我使用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'
>>> 

I think a few things may be helpful. 我认为一些事情可能会有所帮助。

It looks like you're on a windows system, so you should use double back slashes '\\\\' to separate the folders. 看起来你在Windows系统上,所以你应该使用双反斜杠'\\\\'来分隔文件夹。

Second, if you're trying to change to a folder within the current folder, you should use a single dot, and not two, eg os.chdir('.\\\\folder') 其次,如果您尝试更改为当前文件夹中的文件夹,则应使用单个点,而不是两个,例如os.chdir('。\\\\ folder')

Finally, if the folder you are trying to access is not a direct subfolder of the current working directory (or otherwise in your path), you need to include the full path to access it. 最后,如果您尝试访问的文件夹不是当前工作目录的直接子文件夹(或路径中的其他文件夹),则需要包含访问它的完整路径。 Since you said it's on your desktop, you'd probably want something that looks like this: 既然你说它在你的桌面上,你可能想要这样的东西:

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

From here, you could also change directories to the chapter3 subdirectory with the following 从这里,您还可以使用以下内容将目录更改为chapter3子目录

os.chdir('chapter3') 

Which is equivalent in this case with 在这种情况下,这相当于

os.chdir('.\\chapter3')

or, if you want to be wordy: 或者,如果你想罗嗦:

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

Hopefully that helps? 希望这有帮助吗?

I had the same problem before.I solve this when I found that if I created a file on my desktop, the file image would be shown on my desktop, but it will not exist in C/users/Desktop. 之前我遇到了同样的问题。当我发现如果我在桌面上创建了一个文件,文件图像将显示在我的桌面上,但是它不会存在于C / users / Desktop中。 Maybe you can check whether your file is exist in your C drive's desktop or not. 也许您可以检查您的文件是否存在于C盘的桌面上。 Hope this will help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM