
2、例如我们可以使用 os 模块的 os.path.exists() 方法来检测文件是否存在:
import os.path
os.path.isfile(fname)
3、如果你要确定他是文件还是目录,从 Python 3.4 开始可以使用 pathlib 模块提供的面向对象的方法 (Python 2.7 为 pathlib2 模块):
from pathlib import Path
my_file = Path(/path/to/file)
if my_file.is_file():
# 指定的文件存在
检测是否为一个目录:
if my_file.is_dir():
# 指定的目录存在
4、如果要检测路径是一个文件或目录可以使用 exists() 方法:
if my_file.exists():
# 指定的文件或目录存在
在 try 语句块中你可以使用 resolve() 方法来判断:
try:
my_abs_path = my_file.resolve()
except FileNotFoundError:
# 不存在
else:
# 存在
look~~>>>os.path.exists("te")
True
>>>os.path.exists("nothing")
False
>>>os.path.isfile("nothing")
False
>>>os.path.isdir("nothing")
False
>>>
>>>os.path.isdir("te")
False
>>>os.path.isfile("te")
True
>>>
建议你先判断是否存在,如果确实存在,你再进行判断是文件还是文件夹
-------------------------
Linux,文件夹名和同级目录的文件名是不可以同时存在的。
zhangzhipeng@Earth:~$ mkdir te
mkdir: cannot create directory `te': File exists
zhangzhipeng@Earth:~$ rm te
zhangzhipeng@Earth:~$ mkdir te
zhangzhipeng@Earth:~$ >te
-bash: te: Is a directory
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)