python os.listdir不显示所有文件

2024-10-05 15:30:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的windows7 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)

在运行pythont1.py之后,我什么也得不到。 为什么文件漏了?如何列出文件夹下的所有文件?

顺便说一下:我在Windows764bit下使用的是Python3.3.032bit版本


Tags: 文件pyimport文件夹oswindows系统files
3条回答

我不认为这是一个特定于Python的问题。在运行64位操作系统时,Windows确实有32位进程的有趣之处。在这种情况下,运行32位python时,Windows可能会将C:\ Windows\SysWOW64\的内容显示为system32。SysWOW64包含用于32位兼容层的各种Windows组件的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([])

在64位Windows上运行的32位进程具有可用于此问题的sysnative别名。

C:\Windows\System32>systeminfo | find "System Type"
System Type:               x64-based PC

C:\Windows\System32>dir /b msconfig.exe
msconfig.exe

C:\Windows\System32>python
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> 'msconfig.exe' in os.listdir(r'c:\windows\system32')
False
>>> 'msconfig.exe' in os.listdir(r'c:\windows\sysnative')
True
>>>

File System Redirector (MSDN),上面写着:

32-bit applications can access the native system directory by substituting %windir%\Sysnative for %windir%\System32.

尝试: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)

相关问题 更多 >