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