Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do os.path.isfile return False?

Tags:

python-2.7

I am just a newbie in python, so sorry for noobish question

>>> import os >>> os.listdir("/home/user/Desktop/1") ['1.txt', '2', '3.txt'] >>> os.path.isfile("/home/user/Desktop/1/1.txt") True >>> for i in os.listdir("/home/user/Desktop/1"): ...     print(os.path.isfile(i)) ... False False False >>> 

two of them are files then why the output is False when it should be True?

like image 865
Shaurya Gupta Avatar asked Jul 27 '13 01:07

Shaurya Gupta


People also ask

What does the OS path Isfile return?

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.

What does OS path exists do?

path. 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.

How do you check if a file exists in a dir?

path. isdir() method checks if a directory exists. It returns False if you specify a path to a file or a directory that does not exist. If a directory exists, isdir() returns True.

How do you check if a file is present in Python?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .


2 Answers

The problem is with your CWD (Current Working Directory) because os.listdir() give you files whose are relative to the provided path and it's inconsistent with CWD. The solution is to set your CWD before using os.listidr():

dir_to_delete = '/home/user/Desktop/1'  os.chdir(dir_to_delete)  [f for f in os.listdir() if os.path.isfile(f)] 

or just repair path to files:

[f for f in os.listdir(dir_to_delete) if os.path.isfile(os.path.join(dir_to_delete, f))] 
like image 32
Robert Wrzos Avatar answered Oct 06 '22 01:10

Robert Wrzos


When you print os.path.isfile(i), you're checking if "1.txt" or "2" or "3.txt" is a file, whereas when you run os.path.isfile("/home/user/Desktop/1/1.txt") you have a full path to the file.

Try replacing that line with

print(os.path.isfile("/home/user/desktop/1/" + i)) 

Edit:

As mentioned in the comment below by icktoofay, a better solution might be to replace the line with

print(os.path.isfile(os.path.join("/home/user/desktop/1", i))) 

or to earlier store "/home/user/desktop/1" to some variable x, allowing the line to be replaced with

print(os.path.isfile(os.path.join(x,i))) 
like image 159
qaphla Avatar answered Oct 06 '22 00:10

qaphla