os.listdir etc fails on shared windows path (Python 2.5)

时光毁灭记忆、已成空白 提交于 2020-01-17 01:14:55

问题


I am seeing some weird behavior while parsing shared paths (shared paths on server, e.g. \storage\Builds)

I am reading text file which contains directory paths which I want to process further. In order to do so I do as below:

def toWin(path):
    return path.replace("\\", "\\\\")

for line in open(fileName):
    l = toWin(line).strip()
    if os.path.isdir(l):
        print l # os.listdir(l) etc..

This works for local directories but fails for paths specified on shared system.

e.g. 
    E:\Test -- works
    \\StorageMachine\Test -- fails [internally converts to \\\\StorageMachine\\Test]
    \\StorageMachine\Test\ -- fails  [internally converts to \\\\StorageMachine\\Test\\]

But if I open python shell, import script and invoke function with same path string then it works!

It seems that parsing windows shared paths is behaving differently in both cases.

Any ideas/suggestions?


回答1:


This may not be your actual issue, but your UNC paths are actually not correct - they should start with a double backslash, but internally only use a single backslash as a divider.

I'm not sure why the same thing would be working within the shell.

Update: I suspect that what's happening is that in the shell, your string is being interpreted by the shell (with replacements happening) while in your code it's being treated as seen for the first time - basically, specifying the string in the shell is different from reading it from an input. To get the same effect from the shell, you'd need to specify it as a raw string with r"string"




回答2:


There is simply no reason to "convert". Backslashes are only interpreted when they are contained in string literals in your code, not when you read them programmatically from a file. Therefore, you should disable your conversion function and things will probably work.




回答3:


Have to convert input to forward slash (unix-style) for os.* modules to parse correctly.

changed code as below

def toUnix(path):
    return path.replace("\\", "/")

Now all modules parse correctly.



来源:https://stackoverflow.com/questions/2046912/os-listdir-etc-fails-on-shared-windows-path-python-2-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!