如何在Python中枚举文件系统?
我正在使用 os.statvfs
来查看某个存储设备上可用的空闲空间。除了查询特定路径的空闲空间外,我还想能够遍历所有的存储设备。目前我在使用Linux,但我希望能有一种方法,在Linux上能返回 ["/", "/boot", "home"]
这样的结果,而在Windows上能返回 ["C:\", "D:\"]
。
1 个回答
3
对于Linux系统,可以考虑解析一下 /etc/mtab
或者 /proc/mounts
文件。或者:
import commands
mount = commands.getoutput('mount -v')
lines = mount.split('\n')
points = map(lambda line: line.split()[2], lines)
print points
对于Windows系统,我找到了一些类似的内容:
import string
from ctypes import windll
def get_drives():
drives = []
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.uppercase:
if bitmask & 1:
drives.append(letter)
bitmask >>= 1
return drives
if __name__ == '__main__':
print get_drives()
还有这个:
from win32com.client import Dispatch
fso = Dispatch('scripting.filesystemobject')
for i in fso.Drives :
print i
试试这些,可能会对你有帮助。
另外,这个链接也应该能帮到你: 有没有办法在Python中列出所有可用的驱动器字母?