سؤال

I'm learning Python (with Python 3.2) and have been following a few manuals. In one, I was asked to change my current directory to one that contains a particular file I was asked to make and place there. I've been encountering the following error:

>>> import os
>>> os.getcwd()
'C:\\Users\\the mine comp'
>>> os.chdir("../Desktop")
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    os.chdir("../Desktop")
WindowsError: [Error 2] The system cannot find the file specified: '../Desktop'

I have tried these:

os.chdir("/Desktop")
os.chdir("\Desktop")
os.chdir(r"/Desktop")
os.chdir(r"\Desktop")
os.chdir("../Desktop")
os.chdir("..\Desktop")
os.chdir(r"../Desktop")
os.chdir(r"..\Desktop")

The only related information I found before resorting to asking here was utilizing raw strings for Windows path variables (sadly this is all happening on a Vista netbook), and normalizing the pathname with normpath(path). I have tried the former as displayed above (am I using it right?), and I don't fully understand how to utilize the latter, or if it is even applicable to my problem.

The only other bit I've come across is that I may be invoking an escape character using backslashes in strings, but the raw string syntax ought to have taken care of that issue, right? Also, I should note that the directory I am aiming to get to is this:

 C:\users\the mine comp\Desktop

Any suggestions?

هل كانت مفيدة؟

المحلول

The / or \ forms are for changing to an absolute path. You have to know the entire path from start to finish for it to succeed.

The .. forms are for changing up a directory. You only need them if you're moving upwards or "sideways".

Try just os.chdir("Desktop"). You're already in the C:\users\the mine comp\ directory, so you don't need to move up or move to an absolute location. (Consider, if you wanted to open a file in the directory -- you just name the file. Same thing for subdirectories.)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top