本文介绍了os.walk() 在使用 UNC 路径时不处理子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我在 Windows 上的 python 2.7.8 中使用 os.walk() 时遇到问题.

I'm having trouble with os.walk() in python 2.7.8 on Windows.

当我为它提供正常"路径(例如 "D:\Test\master")时,它会按预期工作.但是,当我为它提供一个 UNC 路径,例如 "\\?\D:\Test\master" 时,它会按预期报告根目录,但不会深入到子目录,也不会会不会引发异常.

When I supply it with a 'normal' path such as "D:\Test\master" it works as expected. However when I supply it with a UNC path such as "\\?\D:\Test\master" it will report the root directory as expected but it will not drill down into the sub directories, nor will it raise an exception.

我的研究:我在帮助页面上阅读了os.walk() 接受一个函数参数来处理错误.默认情况下,此参数为 None,因此不会报告错误.

My research: I read on the help page that os.walk() accepts a function argument to handle errors. By default this argument is None so no error is reported.

我传递了一个简单的函数来打印错误并收到每个目录的以下内容.

I passed a simple function to print the error and received the following for every directory.

def WalkError(Error):
    raise Exception(Error)

堆栈跟踪:

Traceback (most recent call last):
  File "Compare.py", line 988, in StartServer
    for root, dirs, files in os.walk(ROOT_DIR,True,WalkError):
  File "C:\Program Files (x86)\Python2.7.8\lib\os.py", line 296, in walk
    for x in walk(new_path, topdown, onerror, followlinks):
  File "C:\Program Files (x86)\Python2.7.8\lib\os.py", line 281, in walk
    onerror(err)
  File "Compare.py", line 62, in WalkError
    raise Exception(Error)
Exception: [Error 123] The filename, directory name, or volume label syntax is incorrect: '\\\\?\\D:\\Test\\master\\localization/*.*'

推荐答案

来自原作者的回答(最初发布为对问题的编辑):

Answer from the original author (originally posted as an edit to the question):

即时更新:在检查\lib\os.py的过程中,发现错误源于os.listdir().我搜索了与 os.listdir() 相关的上述错误消息,并找到了 此解决方案这对我有用.

Instant update: In the process of inspecting \lib\os.py, I discovered the error stems from os.listdir(). I searched for the above error message in relation to os.listdir() and found this solution which worked for me.

看起来如果您要使用带有 os. 模块的 UNC 样式路径,它们需要 Unixised(将它们的 \ 转换为 /代码>).\\\\?\\D:\\Test\\master\\ 变为 //?/D:/Test/master/ (注意:您不再需要转义 \ 这很方便).

It looks like if you're going to use UNC style paths with os. modules they need to Unixised (have their \ converted to /). \\\\?\\D:\\Test\\master\\ becomes //?/D:/Test/master/ (note: you no longer need to escape the \ which is handy).

这与 UNC规范"背道而驰知道您是否正在使用其他尊重 Microsoft UNC 实现的模块.

This runs counter to the UNC 'spec' so be aware if you're working with other modules which respect Microsoft's UNC implementation.

(对不起,我自己解决了,我打算关闭标签,但觉得这里有其他地方找不到的知识.)

(Sorry for the self-solution, I was going to close the tab but felt there was knowledge here which couldn't be found elsewhere.)

这篇关于os.walk() 在使用 UNC 路径时不处理子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 17:34