views:

72

answers:

3

Whenever I call os.path.exists(variable) it will return false but if I call os.path.exists('/this/is/my/path') it will return true.

import os
import sys

test = None
print("Test directory")
test= sys.stdin.readline()
test.strip('\n')
print(os.path.exists(test))

I know that os.path.exists can return false if there is a permissions error but the directories I reference have no restrictions. Sometimes my paths have spaces in them. I have tries passing the path as both '/this\ is/my/path' and '/this is/my/path with the same results.

+6  A: 

You have to do

test = test.strip("\n")

Strings are immutable, so strip() returns a new string.

(At least your code works for me then, if it is still not working for you, it must be something else.)

Felix Kling
+1  A: 

strip() does not modify the string, it returns a new string. Try this:

import os
import sys
sys.stdout.write("Test directory: ")
test = sys.stdin.readline().strip('\n')
sys.stdout.write(str(os.path.exists(test)) + "\n")

(I'm using sys.stdout.write() instead of print() for Python-3 agnosticity.)

Zack
`print(foo)` works both in Python 2 and 3. `print(foo, bar)` kinda works in Python 2, too. No need to get this ugly in an exampe just to be portable. And in real code, you'd write it for one and convert it via `2to3` or `3to2`...
delnan
Huh, learn something new every day. I guess Python 2's treating parentheses as a tuple constructor? Honestly, in real code I prefer `[sys.]stdout.write` to `print` anyway, 'cos I'm a less-magic sort of guy.
Zack
`(expression)` itself is just `expression`, but `(expr1, expr2)` is a tuple, yes. But why avoid print? It's no "magic" (it takes less than 10 straighforward lines to re-implement in Python), just a realy useful function.
delnan
@Zack: Why would `sys.stdout.write` be less magic than `print`? I understand if you claim that `<filehandle_I_own>.write` is less "magic" than `print`, but `print` is dead simple - it writes the data to the current `stdout` handle, which is exactly the same as what `sys.stdout.write` does. Both of them could have been hijacked by any number of things to create "magic", but `sys.stdout.write` isn't immune to such things.
Nick Bastin
I consider all of print's whitespace handling to be magic.
Zack
A: 

Hi, what you would have to do is either:

test = test.strip('\n')

or

print(os.path.exists(test.strip('\n'))

for what they said above, strip() returns a new string so in order for test to have the new string you must reassign it to it. (or in the second case use the new string straight in path.exists())