faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes
Recently 1 of 2 people (50%) answered Yes

Entry

Filename utility routine (drives)

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 59, Tim Peters


"""
Packages: operating_systems.dos;operating_systems.windows
"""

"""
[Guido]
> ...
> ...
> The only thing that's not dealt with quite correctly is drive
> letters.  And I'm not sure that it *can* be dealt with
> correctly -- e.g. C:foo refers to foo relative to the C drive's
> current directory, but there is no way to ask what the that is!

Don't know whether this is portable, but it works on my Win95:
"""

import os
def cwdondrive(drive):
    """cwdondrive(drive): return absolute path to cwd on drive 'drive'"""
    save = os.getcwd()
    try:
        os.chdir(drive + ":")
        return os.getcwd()
    finally:
        os.chdir(save)

"""
E.g., if I start Python in d:/python from a fresh DOS box, and call
cwdondrive("c"), it returns r"c:\windows\desktop" without changing my cwd
(well, ok, after changing it twice <wink>).

And weak attempts to fool it didn't.

close-enough-for-government-work<wink>-ly y'rs  - tim
"""

# example by PSST
print cwdondrive("c")