简体   繁体   中英

python os.listdir doesn't show all files

In my windows7 64bit system, there is a file named msconfig.exe in folder c:/windows/system32 . Yes, it must exists.

But when i use os.listdir to search the folder c:/windows/system3 2, I didn't get the file. Here is the test code, in t1.py :

import os
files = os.listdir("c:/windows/system32")
for f in files:
    if f.lower() == "msconfig.exe":
        print(f)

After run python t1.py , I get nothing. Why the file missed? How can I list all files under a folder?

BTW: I am using python 3.3.0 32bit version under windows 7 64bit

I don't think this is a Python-specific issue. Windows does interesting things with 32 bit processes when running a 64 bit OS. In this case, Windows is probably showing you the contents of C:\\Windows\\SysWOW64\\ as system32 when running 32 bit python. SysWOW64 contains 32 bit versions of various Windows components for use with the 32 bit compatibility layer.

The following was run on a Windows 7 x64 system; explorer.exe (which in this case is 64 bit) definitely shows different contents for these folders, yet:

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([])

A 32-bit process running on 64-bit Windows has the sysnative alias available for this problem.

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
>>>

See File System Redirector (MSDN) , which says:

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

try: C:\\Windows\\System32 instead of c:/windows/system32

import os,sys

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM