Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python path.exists() returning False

Tags:

I'm building a basic file server and my program cannot find files.

def sendfile(sock, myfile):     print 'Serving file:', myfile     print 'File exists?:', os.path.exists(myfile)      path = os.path.normpath(os.path.join(os.getcwd(), myfile))     print 'Serving file:', path     print 'File exists?:', os.path.exists(path) 

These always return False even though the 'myfile' and 'path' are correct [the file is in the same directory as the server program].

IDLE works fine, but without passing to functions.

>>> print os.path.exists("/user/server/foo.txt")   True 

What have I missed?

[EDIT:] Output:

Serving file: foo.txt  File exists?: False Serving file: /user/server/foo.txt  File exists?: False 
like image 615
schroeder Avatar asked Sep 26 '12 20:09

schroeder


People also ask

What is the use of exists () in Python?

exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not. Parameter: path: A path-like object representing a file system path.

How do I check if a directory exists in Python?

os. path. isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True.

What does OS path exists return?

os. The path. exist() function is a built-in function provided by the os module. This function takes the path file and returns 'true' if the file is present.

What does OS path Isfile () do?

The os. path. isfile() is an inbuilt Python function that returns True if the path is an absolute pathname. On Unix, that means it begins with a slash; on Windows, it begins with a (back)slash after chopping off a potential drive letter.


1 Answers

I'm almost 100% sure you're not sanitizing your input before you check if the path exists. Here's something I ran in my interpreter:

>>> from os.path import exists >>> exists('dog.png') True >>> exists('dog.png\n') False 

Try stripping whitespace on path before you check if it exists.

like image 65
Thane Brimhall Avatar answered Nov 10 '22 00:11

Thane Brimhall