tags:

views:

178

answers:

3

Hi,

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?

A: 

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"

fencepost
See updates. They are starting with \\Storage.. I don't understand what you are implying.
Ketan
Updated. I suspect that it works in the shell because the shell is interpreting the string when you enter it, while the value read from an input file is passed raw.
fencepost
I am reading path names from the file and need to convert it to correct form. How do I make string read from file (via readlines) to raw form so that os.* can process.
Ketan
A: 

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.

Ketan
Your explanation is most likely wrong. os.* functions are perfectly able to deal with paths containing backslashes, as long as your OS is able to interpret them. See my own answer to your question.
Antoine P.
A: 

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.

Antoine P.
This input is coming from someone which contains windows paths and they will be in \. So convertion ensures that in whatever form input comes, it will work.
Ketan
So what? If you are under Windows, Windows paths will work perfectly well.
Antoine P.