Search code examples
python-3.xfileif-statementpathlib

Erroneous Output for Path Check in Python 3.6


I was just experimenting with the pathlib library in Python 3.6. I wanted to check if such a file with the given file name exists in the path that I have given. Here is my code:

from pathlib import Path
f = Path('/Libraries/Documents/sample.txt')
print("File {} Exists".format(f)) if f.exists() else print("False")

And the output that I got was:

>>> False

while such a file truly existed in that path.

What could be the possible error in the above code?


Solution

  • It works well when I made a small modification to the above code.

    import pathlib
    f = pathlib.Path(r'C:\Users\user\Documents\sample.txt')
    print("File {} Exists".format(f)) if f.exists() else print("False")
    

    And I got the correct output this time

    >>> File C:\Users\user\Documents\sample.txt Exists 
    

    I figured out that I got erroneous output previously because I had missed that r in path specification