3

On Windows 7 I fire up my IDLE Python 2.7.5 Shell:

>>> import os
>>> os.getcwd()
'C:\\Python27'
>>> os.path.relpath('C:\\')
'..'
>>> os.path.relpath('C:')
'.'
>>> os.chdir('C:')
>>> os.getcwd()
'C:\\Python27'

What is going on, and why does it have to be this complicated?

Bleeding Fingers
  • 6,993
  • 7
  • 46
  • 74
Scruffy
  • 908
  • 1
  • 8
  • 21
  • 3
    This all makes sense. `C:` without a path designation represents the current directory on drive `C:`. So the relative path is `.` since you are on drive `C:` And since you are at `C:\\Python27`, then the relative path to `C:\\` is `..`. – lurker Sep 08 '13 at 01:07
  • 1
    That goes back to DOS days, where "cd X:" would take you to the last directory you were in on X:, not necessarily the root directory of X:. – Kirk Strauser Sep 08 '13 at 01:18

2 Answers2

1

You are not trying to change to actual folder, but to "c:", proper command will be

import os 
os.chdir('c:\\')

And it will work just fine. The reason for double backslash is to escape the backslash (which works as escape character).

Tymoteusz Paul
  • 2,732
  • 17
  • 20
  • Ok, but why is it set up this way? To me 'c:' should mean the root folder 'c:\'. Is there a good reason for 'c:' to still 'be' in a particular folder. Do all drives have a 'cwd' at all times? – Scruffy Sep 08 '13 at 01:16
  • @Scruffy that sounds like a fabulous thing for you to test out (and it is easy, altogether with being a fun exercise, i promise!). As for why, it is a leftover that windows inherited from very old times. – Tymoteusz Paul Sep 08 '13 at 01:18
  • @Scruffy As I explain in my answer, this depends on how you run Python. – Mike Vella Sep 08 '13 at 01:20
  • 1
    @Scruffy: "To me 'c:' should mean the root folder 'c:\'." -- but you didn't invent DOS, so it's not your call ;-) When Python runs on Windows it makes sure that paths beginning with "C:" mean the same thing in Python as they do to Windows. – Steve Jessop Sep 08 '13 at 01:29
  • Yes, all drives have a current directory at all times. (Well, to all effects and purposes.) This is remarkably useful at the command line. – Harry Johnston Sep 11 '13 at 04:36
1

On Windows the behaviour can be a bit strange - it behaves differently if you start Python from cmd.exe or if you start it directly (not going through cmd.exe). As has been pointed out the correct command is os.chdir('c:\\'). this answer provides more detail.

Community
  • 1
  • 1
Mike Vella
  • 10,187
  • 14
  • 59
  • 86