在python中更改当前工作目录

2024-06-09 00:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我在桌面上创建了一个名为“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'
>>> 

Tags: 目录文件夹mostoscallfilelastchapter
2条回答

我想有些事情可能会有帮助。

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

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

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

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

从这里,您还可以使用以下命令将目录更改为chapter3子目录

os.chdir('chapter3') 

在这种情况下与

os.chdir('.\\chapter3')

或者,如果你想多说:

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

希望能帮上忙?

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

相关问题 更多 >