Python#39;s os.listdir behaviour on Windows(Windows 上 Python 的 os.listdir 行为)
问题描述
>>> 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:WindowsC:Foo将引用C:Foo
.would refer toD:Datawould refer toD:C:would refer toC:WindowsC:Foowould refer toC:Foo
因此,如果您想获得有关特定目录的信息,则应始终使用完整路径包括驱动器和目录,如 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 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Windows 上 Python 的 os.listdir 行为
基础教程推荐
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
