ディレクトリやファイルが存在するか調べる

ディレクトリやファイルが存在するか調べるには os.path.exists() を使います。

ディレクトリが存在するか調べるには os.path.isdir() を使います。

ファイルが存在するか調べるには os.path.isfile() を使います。

import os

# --------------------------------------------

path0 = "c:/tmp"
print( path0 )

if ( os.path.exists( path0 ) == True ):
    
    if ( os.path.isfile( path0 ) == True ):
        print( "it is file." )
    else:
        print( "it is not file." )

    if ( os.path.isdir( path0 ) == True ):
        print( "it is dir." )
    else:
        print( "it is not dir." )

else:
    print( "dir or file is not exist." )
    
# --------------------------------------------

path1 = "c:/tmp/test_1024_0768.bmp"
print( path1)

if ( os.path.exists( path1 ) == True ):

    if ( os.path.isfile( path1 ) == True ):
        print( "it is file." )
    else:
        print( "it is not file." )

    if ( os.path.isdir( path1 ) == True ):
        print( "it is dir." )
    else:
        print( "it is not dir." )

else:
    print( "dir or file is not exist." )
        
# --------------------------------------------
        
print( "finish" )

下記が実行結果です。

c:/tmp
it is not file.
it is dir.
c:/tmp/test_1024_0768.bmp
it is file.
it is not dir.
finish