os.getcwd() for a different drive in Windows

前端 未结 3 1554
天涯浪人
天涯浪人 2021-01-11 11:50

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

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

This is giv

相关标签:
3条回答
  • 2021-01-11 12:39

    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)
    0 讨论(0)
  • 2021-01-11 12:40

    This is factually incorrect. Each process has a single working directory. There is no separate working directory for different drives.

    For a historical perspective, have a read of this article by Raymond Chen.

    0 讨论(0)
  • 2021-01-11 12:42

    I believe that the section you are reading that from is worded poorly. There is only one current working directory for your python session, and you get it from os.getcwd(). You can use os.chdir(r'F:\') to change directories to your F drive.

    The part that that quote is referencing is relating to the os.path.join method. It means that passing a first argument of 'C:' instead of r'C:\', you will get the incorrect path (namely C:path instead of C:\\path).

    0 讨论(0)
提交回复
热议问题