[英]change current working directory in 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'
>>>
我认为一些事情可能会有所帮助。
看起来你在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盘的桌面上。 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.