Change current working directory in python

I made a folder on my desktop with the name "headfirstpython", and I need to change the current working directory to this folder and its internal folder. I used os.getcwd () to get the current folder, and that gives me "C \ Python32". I used os.chdir ('../ headfirstpython / chapter3') to change the directory, but it says that it cannot find the path

>>> 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' >>> 
+11
python
source share
2 answers

I think some things may be helpful.

It looks like you are on a Windows system, so you need to use double backslashes "\\" to separate folders.

Secondly, if you are trying to navigate to a folder in the current folder, you should use one point, not two, for example. os.chdir ('. \\ folder')

Finally, if the folder you are trying to access is not a direct subfolder of the current working directory (or else in your path), you need to include the full path to access it. Since you said this on your desktop, you probably want something similar to this:

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

Here you can also change directories in the Chapter3 subdirectory with the following

 os.chdir('chapter3') 

Which is equivalent in this case with

 os.chdir('.\\chapter3') 

or, if you want to be verbose:

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

Hope this helps?

+4
source share

I had the same problem before. I solved this problem when I found that if I create a file on my desktop, the image of the file will be displayed on my desktop, but it will not be in C / users / Desktop. Maybe you can check if your file exists on the desktop of your C drive or not. Hope this helps.

-one
source share

All Articles