目录
os.path模块
os.path模块提供了目录相关 ( 路径判断, 路径切分, 路径连接, 文件夹遍历 ) 的操作;
方法 | 描述 |
isabs(path) | 判断path是否绝对路径 |
isdir(path) | 判断path是否为目录 |
isfile(path) | 判断path是否为文件 |
exists(path) | 判断指定路径的文件是否存在 |
getsize(filename) | 返回文件的大小 |
abspath(path) | 返回绝对路径 |
dirname(p) | 返回目录的路径 |
getatime(filename) | 返回文件的最后访问时间 |
getmtime(filename) | 返回文件的最后修改时间 |
walk(top,func,arg) | 递归方式遍历目录 |
join(path,*paths) | 连接多个path |
split(path) | 对路径进行分割,以列表形式返回 |
splitext(path) | 从路径中分割文件的扩展名 |
#coding=utf-8
#测试os.path中关于目录,路径的操作
import os
# import os.path
from os import path #这样写也可以,同import os.path
############判断:绝对路径,是否目录,是否文件,文件是否存在##################
print(os.path.isabs("D:\wwwroot\pyiteam\my02.txt")) #True 是否是绝对路径
print(os.path.isdir("D:\wwwroot\pyiteam\my02.txt")) #False 是否为目录
print(os.path.isfile("D:\wwwroot\pyiteam\my02.txt"))#True 是否为文件
print(os.path.exists("D:\wwwroot\pyiteam\my02.txt"))#True 文件是否存在
#########获取文件基本信息###################
print(os.path.getsize("D:\wwwroot\pyiteam\my02.txt"))#10个字节 返回文件大小
print(os.path.abspath("D:\wwwroot\pyiteam\my02.txt"))#D:\wwwroot\pyiteam\my02.txt 获得绝对路径
print(os.path.dirname("D:\wwwroot\pyiteam\my02.txt"))#D:\wwwroot\pyiteam 获得文件目录的路径
print(os.path.getatime("D:\wwwroot\pyiteam\my02.txt"))#最后访问时间
print(os.path.getmtime("D:\wwwroot\pyiteam\my02.txt"))#最后修改时间
##########对路径的操作#######################
path = os.path.abspath("D:\wwwroot\pyiteam\my02.txt")
print(os.path.split(path))#对路径进行切割,返回元组
print(os.path.splitext(path))#对扩展名进行切割,返回元组,拿到扩展名
print(os.path.join("aa","bb","cc")) #aa\bb\cc 路径的连接
输出:
D:\wwwroot\pyiteam\venv\Scripts\python.exe D:/wwwroot/pyiteam/mypro_obj/mypy02.py
True
False
True
True
9
D:\wwwroot\pyiteam\my02.txt
D:\wwwroot\pyiteam
1585672902.1488278
1585672902.1488278
('D:\\wwwroot\\pyiteam', 'my02.txt')
('D:\\wwwroot\\pyiteam\\my02', '.txt')
aa\bb\cc
Process finished with exit code 0
#coding=utf-8
#列出工作目录下所有的.py文件,并输出文件名
import os
path = os.getcwd() #工作目录
file_list = os.listdir(path) #列出子目录,子文件
for filename in file_list:
if filename.endswith("py"):# endswith 用于判断字符串中某段字符串是否以指定字符或子字符串结尾
print(filename,end="\t")
print()
print("#列表推导式实现上述代码")
file_list2 = [filename for filename in os.listdir(path) if filename.endswith("py")]
for f in file_list2:
print(f,end="\t")
输出:
D:\wwwroot\pyiteam\venv\Scripts\python.exe D:/wwwroot/pyiteam/mypro_obj/mypy02.py
mypy01.py mypy02.py
#列表推导式实现上述代码
mypy01.py mypy02.py
Process finished with exit code 0