首页 > 解决方案 > 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

标签: python

解决方案


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来自哪个目录。


推荐阅读