Windows上Python的os.listdir行为 [英] 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', 'windows']
"c:"后面的"/"为什么会影响结果?有没有办法让os.listdir('c:')
返回"c:/"的内容?
Why is the "/" after "c:" affecting the outcome? Is there a way to get os.listdir('c:')
to return the contents of "c:/"?
推荐答案
这并非特定于Python,而是Windows的核心问题.
This is not specific to Python, it's a Windows question at heart.
在Windows中,C:
和C:\
(或C:/
)具有完全不同的含义:
In Windows C:
and C:\
(or, alternatively C:/
) have quite different meanings:
-
C:
引用驱动器C:
上的当前目录
-
C:\
(和C:/
)引用驱动器C:
的根目录
C:
refers to the current directory on the driveC:
C:\
(andC:/
) refers to the root directory of the driveC:
虽然类似UNIX的操作系统仅具有一个当前目录",但Windows具有两个独立的概念:
While UNIX-like operating systems simply have a "current directory", Windows has two separate notions:
- 当前驱动器和
- 每个驱动器的当前目录
因此,当前驱动器可能是D:
,C:
上的当前目录可以是\Windows
(有效地C:\Windows
),而D:
上的当前目录可以是\Data
(有效地D:\Data
) .在这种情况下,解析将像这样工作:
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:\Data
-
\
指的是D:\
-
C:
指的是C:\Windows
-
C:\Foo
将引用C:\Foo
.
would refer toD:\Data
\
would refer toD:\
C:
would refer toC:\Windows
C:\Foo
would refer toC:\Foo
因此,如果要获取有关特定目录的信息,则应始终使用 full 路径包括驱动器和目录,例如C:\
.
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:\
.
这篇关于Windows上Python的os.listdir行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!