os.listdir看不到我的目录

Jas*_*ray 4 python windows windows-8.1

我正在研究在Windows 8.1计算机上安装802.1x证书的python脚本。该脚本在Windows 8和Windows XP上运行良好(尚未在其他计算机上尝试过)。

我已经隔离了这个问题。它与清除文件夹有关

"C:\Windows\system32\config\systemprofile\AppData\LocalLow\Microsoft\CryptURLCache\Content"
Run Code Online (Sandbox Code Playgroud)

问题是我在此文件夹上使用模块os和命令listdir删除其中的每个文件。但是,listdir错误,表示该文件夹确实存在时不存在。

问题似乎是os.listdir看不到LocalLow文件夹。如果我编写了两行脚本:

import os

os.listdir("C:\Windows\System32\config\systemprofile\AppData") 
Run Code Online (Sandbox Code Playgroud)

它显示以下结果:

['Local', 'Roaming']
Run Code Online (Sandbox Code Playgroud)

如您所见,LocalLow丢失了。

我以为这可能是权限问题,但是我在确定下一步可能会遇到麻烦。我正在以管理员身份从命令行运行该过程,但是根本看不到该文件夹​​。

提前致谢!

编辑:将字符串更改为r“ C:\ Windows \ System32 \ config \ systemprofile \ AppData”,“ C:\ Windows \ System32 \ config \ systemprofile \ AppData”或C:/ Windows / System32 / config / systemprofile / AppData “全部产生相同的结果

编辑:此问题的另一个不寻常之处:如果在该位置手动创建新目录,则无法通过os.listdir看到它。此外,我无法通过Notepad ++中的“另存为...”命令浏览到LocalLow或我的新文件夹。

我开始认为这是Windows 8.1预览版中的错误。

小智 8

我最近遇到了这个问题。

我发现这是Windows文件系统重定向器引起的

您可以查看以下python代码段

import ctypes

class disable_file_system_redirection:
    _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
    _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
    def __enter__(self):
        self.old_value = ctypes.c_long()
        self.success = self._disable(ctypes.byref(self.old_value))
    def __exit__(self, type, value, traceback):
        if self.success:
            self._revert(self.old_value)


#Example usage
import os

path = 'C:\\Windows\\System32\\config\\systemprofile\\AppData'

print os.listdir(path)
with disable_file_system_redirection():
    print os.listdir(path)
print os.listdir(path)
Run Code Online (Sandbox Code Playgroud)

参考:http : //code.activestate.com/recipes/578035-disable-file-system-redirector/


小智 5

您的路径中必须有转义序列。您应该使用原始字符串作为文件/目录路径:

# By putting the 'r' at the start, I make this string a raw string
# Raw strings do not process escape sequences
r"C:\path\to\file"
Run Code Online (Sandbox Code Playgroud)

或者以另一种方式放置斜杠:

"C:/path/to/file"
Run Code Online (Sandbox Code Playgroud)

或转义斜杠:

# You probably won't want this method because it makes your paths huge
# I just listed it because it *does* work
"C:\\path\\to\\file"
Run Code Online (Sandbox Code Playgroud)

  • @JeffBridgman - 当你发表评论时我刚刚打字。:) (2认同)