Python os.listdir behavior on Windows

>>> import os >>> os.chdir('c:/python27') >>> os.listdir('c:') ['Tools', 'include', 'python.exe', 'libs', 'DLLs', 'Lib', 'NEWS.txt', 'w9xpopen.exe', 'Doc', 'pythonw.exe', 'LICENSE.txt', 'README.txt', 'tcl'] >>> os.listdir('c:/') ['users', 'Program Files', 'Python27', 'windows'] 

Why does the "/" after "c:" affect the result? Is there a way to get os.listdir('c:') to return the contents of "c: /"?

+8
python windows operating-system
source share
2 answers

I don't think this is specific to Python, this is a Windows issue at heart.

On Windows, C: and C:\ (or, alternatively, C:/ ) have completely different meanings:

  • C: refers to the current directory on drive C:
  • C:\ (and C:/ ) refers to the root directory of drive C:

While UNIX-like operating systems simply have a "current directory", Windows has two different concepts:

  • current drive and
  • current directory to disk

Thus, the current drive can be D: current directory on C: can be \Windows (effectively C:\Windows ), and the current directory on D: can be \Data (effectively D:\Data )). In this scenario, the resolution will work as follows:

  • . will refer to D:\Data
  • \ will refer to D:\
  • C: will refer to C:\Windows
  • C:\Foo will refer to C:\Foo

So, if you want to have information about a specific directory, you should always use the full path, including both the drive and the directory, for example C:\ .

+21
source share

C: uses the current working directory on drive C :.

C: / translates to C: \ and uses the root directory on the C: drive.

Is there a way to get os.listdir ('c:') to return the contents of "c: /"?

Not.

However, you can change directories. But it can confuse users.

+3
source share

All Articles