Python检测文件或文件夹是否存在

通过os.path模块来检测某个文件或目录是否存在。

os.path.exists(path)

可以用来检测文件或文件夹是否存在:

1
2
3
4
5
6
7
# Test whether a path exists
>>> import os
>>> os.path.exists('/etc/passwd')
True
>>> os.path.exists('/tmp/spam')
False
>>>

os.path.isfile(path)

用来检测文件是否存在:

1
2
3
4
5
6
7
# Test whether a path is a regular file
>>> import os
>>> os.path.isfile('/etc/passwd')
True
>>> os.path.isfile('/etc')
False
>>>

os.path.isdir(path)

用来检测文件夹是否存在:

1
2
3
4
5
6
7
# Test whether a path is a directory.
>>> import os
>>> os.path.isdir('/etc/passwd')
False
>>> os.path.isdir('/etc')
True
>>>

用来检测是否是符号链接

1
2
3
4
5
6
# Test whether a path is a symbolic link
>>> os.path.islink('/usr/bin/python')
True
>>> os.path.islink('/usr/bin/python2.7')
False
>>>

可以用os.path.realpath(path)找到符号链接所指向的文件路径:

1
2
3
4
5
# Get the file linked to
>>> import os
>>> os.path.realpath('/usr/bin/python')
'/usr/bin/python2.7'
>>>

如果需要得到元数据(即,文件大小或修改日期),这些功能在os.path模块中也有提供:

1
2
3
4
5
6
7
8
9
>>> import os
>>> os.path.getsize('/etc/passwd')
1453
>>> os.path.getmtime('/etc/passwd')
1487564480.554474
>>> import time
>>> time.ctime(os.path.getmtime('/etc/passwd'))
'Mon Feb 20 12:21:20 2017'
>>>

大师兄 wechat
欢迎关注我的微信公众号:Python大师兄