Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.getcwd() for a different drive in Windows

Tags:

python

According to http://docs.python.org/library/os.path.html

"On Windows, there is a current directory for each drive"

This is giving me some trouble when I use os.getcwd() on Windows.

I am using Python 2.7 on my C drive to call a script located on the shared network drive F:. Yet, os.getcwd() from within this script is returning a directory on my C drive.

Is there anything I can do to get the working directory for my F drive?

like image 544
cssndrx Avatar asked Jul 07 '11 17:07

cssndrx


1 Answers

Actually, it depends:

If Python is started directly (not going through cmd.exe), then yes, you only have the one current directory (it's like always specifying cd /d ...):

--> import os
--> os.getcwd()
'c:\\source\\dbf-dev'
--> os.chdir('z:')
--> os.getcwd()
'Z:\\'
--> os.chdir('c:')    # assumes root directory
--> os.getcwd()
'C:\\'

But, if you start Python from cmd.exe, you get the historical perspective:

>>> import os
>>> os.getcwd()
'Z:\\perm-c'
>>> os.chdir('c:')    # does not assume root directory
>>> os.getcwd()
'C:\\Source\\Path'
>>> os.chdir('d:')
>>> os.getcwd()
'D:\\'
>>> os.chdir('l:')
>>> os.getcwd()
'L:\\'
>>> os.chdir('l:\\letter')
>>> os.getcwd()
'l:\\letter'
>>> os.chdir('z:')
>>> os.getcwd()
'Z:\\perm-c'
>>> os.chdir('l:\\')
>>> os.getcwd()
'l:\\'

Undoubtedly this is an artifact of cmd.exe doing its thing behind the scenes.

To answer your original question, though -- the only way to find out the current directory on drive f: is

  • 1) to have started Python from cmd.exe
  • 2) os.chdir() to 'f:'
  • 3) os.getcwd()
  • 4) os.chdir() back (if desired)
like image 80
Ethan Furman Avatar answered Sep 18 '22 12:09

Ethan Furman