Shaurya Gupta
Shaurya Gupta

Reputation: 567

Why does os.path.isfile return False?

>>> 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, why is the output False when it should be True?

Upvotes: 53

Views: 106987

Answers (2)

Robert Wrzos
Robert Wrzos

Reputation: 111

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))]

Upvotes: 11

qaphla
qaphla

Reputation: 4733

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)))

Upvotes: 54

Related Questions