Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

python 2.7 - Why do os.path.isfile return False?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...