python - os.path.isfile() 仅当文件在目录中时才返回 true
问题描述
我尝试使用os
分隔文件夹和文件,但仅当文件(或文件夹)与程序位于同一文件夹中时才os.path.isfile()
返回os.path.isdir()
。True
我的代码:
if(os.path.exists(".")): # check if the folder exist
for x in os.listdir("."):
if os.path.isfile( os.path.abspath(x)): print('f', x)
elif os.path.isdir( os.path.abspath(x)): print('d', x)
elif os.path.islink(os.path.abspath(x)): print('l', x)
else: print('n/a', x)
控制台:
d left
f main.py
d right
我在“左”文件夹中查看的代码:
if(os.path.exists(".\\left")): # check if the folder exist
for x in os.listdir(".\\left"):
if os.path.isfile( os.path.abspath(x)): print('f', x)
elif os.path.isdir( os.path.abspath(x)): print('d', x)
elif os.path.islink(os.path.abspath(x)): print('l', x)
else: print('n/a', x)
控制台:
n/a normalFile.txt
n/a normalFolder
我真的不明白为什么os.path.isfile()
并os.path.isdir()
返回False
。
解决方案
os.listdir()
只返回文件名。您需要将它们与目录名称一起加入以获取完整路径。
if(os.path.exists(".\\left")): # check if the folder exist
for x in os.listdir(".\\left"):
fullpath = os.path.join( ".\\left", x)
if os.path.isfile( fullpath): print('f', x)
elif os.path.isdir( fullpath): print('d', x)
elif os.path.islink(fullpath): print('l', x)
else: print('n/a', x)
os.path.abspath()
自己不能这样做,因为它不知道x
来自哪个目录。
推荐阅读
- ionic-framework - 等待离子连接与 ionic-app-scripts 问题
- node.js - 当我连接到 MongoDB 时出现 Mistic 问题
- php - Laravel - 如何用 builder 上的 where 子句包围所有先前的子句?
- ios - 如何快速监控地点 4
- c# - Sharepoint List 检索大数据 C#
- google-plus - google plus 收藏是否有任何关注按钮?
- java - 易失性变量并刷新到主存储器/从主存储器读取
- unity3d - 是否可以从数据库查询 3D 对象到统一场景?
- vuejs2 - Vue模板中的返回值
- java - org.json.JSONException:仅使用 API 28 在字符 0 处输入结束