Python 判断文件/目录是否存在的几种方式

使用 os 模块

1
2
3
4
5
import os
print(os.path.isfile('/tmp'))
print(os.path.isdir('/tmp'))
print(os.path.exists('/tmp'))
print(os.access('/tmp', os.F_OK))

输出结果:

1
2
3
4
5
6
7
8
9
10
>>> import os
>>> print(os.path.isfile('/tmp'))
False
>>> print(os.path.isdir('/tmp'))
True
>>> print(os.path.exists('/tmp'))
True
>>> print(os.access('/tmp', os.F_OK))
True
>>>

使用 open 函数和异常捕获

1
2
3
4
5
6
7
8
9
10
11
12
filePath = '/tmp'
try:
file = open(filePath)
file.close()
except FileNotFoundError:
print("No such file or directory: '%s'" % filePath)
except IsADirectoryError:
print("Is a directory: '%s'" % filePath)
except PermissionError:
print("Permission denied: '%s'" % filePath)
else:
print("File is exist: '%s'" % filePath)

输出结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> filePath = '/tmp'
>>> try:
... file = open(filePath)
... file.close()
... except FileNotFoundError:
... print("No such file or directory: '%s'" % filePath)
... except IsADirectoryError:
... print("Is a directory: '%s'" % filePath)
... except PermissionError:
... print("Permission denied: '%s'" % filePath)
... else:
... print("File is exist: '%s'" % filePath)
...
Is a directory: '/tmp'
>>>

使用 pathlib 模块

1
2
3
4
5
6
import pathlib
filePath='/tmp'
path=pathlib.Path(filePath)
print(path.exists())
print(path.is_file())
print(path.is_dir())

输出结果:

1
2
3
4
5
6
7
8
9
10
>>> import pathlib
>>> filePath='/tmp'
>>> path=pathlib.Path(filePath)
>>> print(path.exists())
True
>>> print(path.is_file())
False
>>> print(path.is_dir())
True
>>>