为什么 os.path.isfile 返回 False? [英] Why do os.path.isfile return False?

查看:54
本文介绍了为什么 os.path.isfile 返回 False?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是一个 Python 新手,很抱歉问这个菜鸟问题

<预><代码>>>>导入操作系统>>>os.listdir("/home/user/Desktop/1")['1.txt', '2', '3.txt']>>>os.path.isfile("/home/user/Desktop/1/1.txt")真的>>>对于 os.listdir("/home/user/Desktop/1") 中的 i:...打印(os.path.isfile(i))...错误的错误的错误的>>>

其中两个是文件,那么为什么输出为 False 而应该为 True?

解决方案

当您打印 os.path.isfile(i) 时,您正在检查是1.txt"还是2"或3.txt"是一个文件,而当你运行 os.path.isfile("/home/user/Desktop/1/1.txt") 你有一个完整的文件路径.

尝试用

替换该行

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

正如 icktoofay 在下面的评论中提到的,更好的解决方案可能是用

替换该行

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

或者更早地将/home/user/desktop/1"存储到某个变量 x,允许用

替换该行

print(os.path.isfile(os.path.join(x,i)))

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?

解决方案

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

这篇关于为什么 os.path.isfile 返回 False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆