Python中的os.listdir()函数不能显示所有文件

7
在我的 Windows 7 64 位系统中,c:/windows/system32 文件夹里有一个名为 msconfig.exe 的文件。是的,它必须存在。
但是当我使用 os.listdir 在文件夹 c:/windows/system32 中搜索时,我没有得到这个文件。以下是测试代码,在 t1.py 中:
import os
files = os.listdir("c:/windows/system32")
for f in files:
    if f.lower() == "msconfig.exe":
        print(f)

在运行python t1.py之后,我什么也没得到。为什么文件丢失了?如何列出文件夹下的所有文件?

顺便说一句:我正在使用Windows 7 64位下的Python 3.3.0 32位版本。


也许你想要 system64 - jamylak
你对 os.access('c:/windows/system32/msconfig.exe', os.R_OK) 有什么看法?另外,如何检查大小写敏感性? - wim
@truease.com 你是在哪里运行这个程序的?是在IDLE中吗? - jamylak
在IPython中,执行os.access("c:/windows/system32/msconfig.exe", os.R_OK)返回False,执行os.path.isfile("c:/windows/system32/msconfig.exe")也返回False。在cmd.exe中,执行dir c:\windows\system32\msconfig.exe可以获取该文件的信息。 - truease.com
我曾试图在Cygwin中找到它,但也失败了。在命令行中输入“cd /cygdrive/c/Windows/System32”,然后执行“ls | grep -i msconfig” 没有任何输出。 - truease.com
显示剩余3条评论
3个回答

9
我认为这不是一个特定于Python的问题。当在64位操作系统上运行32位进程时,Windows会做一些“有趣”的事情。在这种情况下,当运行32位Python时,Windows可能会将C:\Windows\SysWOW64\的内容显示为system32。SysWOW64包含各种Windows组件的32位版本,供32位兼容性层使用。本例是在Windows 7 x64系统上运行的; explorer.exe(在本例中为64位)对这些文件夹的内容肯定有所不同。
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import os
>>> 
>>> s32 = set(os.listdir('C:/Windows/System32'))
>>> s64 = set(os.listdir('C:/Windows/SysWOW64'))
>>> s32-s64 # the difference is an empty set!
set([])

太棒了!节省了我很多时间。 - gies0r

6
在64位的Windows系统上运行的32位进程可以使用sysnative别名来解决这个问题。
C:\Windows\System32>systeminfo | find "System Type"
系统类型:                基于 x64 的 PC
C:\Windows\System32>dir /b msconfig.exe msconfig.exe C:\Windows\System32>python Python 2.7.6 (默认, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32 键入 "help", "copyright", "credits" 或 "license" 来获取更多信息。 >>> import os >>> 'msconfig.exe' in os.listdir(r'c:\windows\system32') False >>> 'msconfig.exe' in os.listdir(r'c:\windows\sysnative') True >>>
请参见文件系统重定向器(MSDN),其中说:

32位应用程序可以通过将%windir%\Sysnative替换为%windir%\System32来访问本机系统目录。


0
尝试使用C:\Windows\System32而非c:/windows/system32
import os,sys

files = os.listdir('C:\Windows\System32')
for x in files:
    if x == ('msconfig.exe'):
        print(x)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接