开发者

Python's os.listdir behaviour 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', 'w开发者_如何学Pythonindows']

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


This is not specific to Python, it's a Windows question at heart.

In Windows C: and C:\ (or, alternatively C:/) have quite different meanings:

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

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

  • the current drive and
  • the current directory per drive

So the current drive could be D:, the current directory on C: could be \Windows (effectively C:\Windows) and the current directory on D: could be \Data (effectively D:\Data). In this scenario resolution would work like this:

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

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


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

C:/ is translated 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:/"?

No.

You can, however, change directories. But that may be confusing to users.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜