Python 在 Windows 上的 os.listdir 行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7258993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python's os.listdir behaviour on Windows
提问by D K
>>> 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 is the "/" after "c:" affecting the outcome? Is there a way to get os.listdir('c:')
to return the contents of "c:/"?
为什么“c:”后面的“/”会影响结果?有没有办法os.listdir('c:')
返回“c:/”的内容?
回答by Joachim Sauer
This is not specific to Python, it's a Windows question at heart.
这不是 Python 特有的,它本质上是一个 Windows 问题。
In Windows C:
and C:\
(or, alternatively C:/
) have quite different meanings:
在 Windows 中C:
和C:\
(或者,或者C:/
)具有完全不同的含义:
C:
refers to the current directory on the driveC:
C:\
(andC:/
) refers to the root directory of the driveC:
C:
指驱动器上的当前目录C:
C:\
(和C:/
) 指的是驱动器的根目录C:
While UNIX-like operating systems simply have a "current directory", Windows has two separate notions:
虽然类 UNIX 操作系统只有一个“当前目录”,但 Windows 有两个不同的概念:
- 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:
所以当前驱动器可以是D:
,当前目录C:
可以是\Windows
(有效C:\Windows
),当前目录D:
可以是\Data
(有效D:\Data
)。在这种情况下,分辨率将如下工作:
.
would refer toD:\Data
\
would refer toD:\
C:
would refer toC:\Windows
C:\Foo
would refer toC:\Foo
.
会参考D:\Data
\
会参考D:\
C:
会参考C:\Windows
C:\Foo
会参考C:\Foo
So if you want to have information about a specificdirectory, you should always use a fullpath includingboth a drive and a directory, such as C:\
.
因此,如果您想获得有关特定目录的信息,则应始终使用包含驱动器和目录的完整路径,例如.C:\
回答by S.Lott
C: uses the current working directory on the C: drive.
C: 使用 C: 驱动器上的当前工作目录。
C:/ is translated to C:\ and uses the root directory on the C: drive.
C:/ 转换为 C:\ 并使用 C: 驱动器上的根目录。
Is there a way to get os.listdir('c:') to return the contents of "c:/"?
有没有办法让 os.listdir('c:') 返回“c:/”的内容?
No.
不。
You can, however, change directories. But that may be confusing to users.
但是,您可以更改目录。但这可能会让用户感到困惑。