[TOC] >[success] # 检测文件路径/获取文件信息 ~~~ 1.路径是否存在 2.文件名字加路径是否存在 3.获取文件内容信息 ~~~ >[danger] ##### 判断文件是否存在 --- isfile ~~~ 1.当我们想判断文件是否存在可以使用 -- isfile 但绝对不是唯一的 ~~~ ~~~ import os path = 'D:\\test' # 判断文件路径 l = os.path.isfile(path) print(l) 打印结果: False ~~~ * 如果文件路径 ~~~ import os path = 'D:\\test\\ttest.py' # 判断文件路径 l = os.path.isfile(path) print(l) 打印结果: True ~~~ >[danger] ##### 万能的判断路径 --- isdir ~~~ 1.只要路径存在就是 true ~~~ ~~~ import os path = 'D:\\test' l = os.path.isdir(path) print(l) 打印结果: True ~~~ >[danger] ##### 获取文件内容时间/大小 ---getmtime/ getsize ~~~ path = 'D:\\test\\ttest.py' l = os.path.getsize(path) t = os.path.getmtime(path) print(l) print(t) 打印结果: 64 1531450117.7175772 ~~~ >[danger] ##### 获取一个目录下所有文件 --- listdir ~~~ import os print(os.listdir('D:\\')) ~~~ * 小技巧 ~~~ import os.path # 获取所有常规文件 names = [name for name in os.listdir('somedir') if os.path.isfile(os.path.join('somedir', name))] # 获取所有地址 dirnames = [name for name in os.listdir('somedir') if os.path.isdir(os.path.join('somedir', name))] ~~~ 字符串的 startswith() 和 endswith() 方法对于过滤一个目录的内容也是很有用的。比如: ~~~ pyfiles = [name for name in os.listdir('somedir') if name.endswith('.py')] ~~~