os.path主要对文件、文件夹进行处理,常用的函数可以分为四类:
解析路径
- split()
将路径分离成路径和文件名
- splitext()
将路径分离成路径和文件后缀
- splitdriver()
将路径费力成盘符和文件路径
import os.path
cur_path = r'D:\PythonProject\TestPython\test.py'
print(os.path.split(cur_path))
print(os.path.splitext(cur_path))
print(os.path.splitdrive(cur_path))
('D:\\PythonProject\\TestPython', 'test.py')
('D:\\PythonProject\\TestPython\\test', '.py')
('D:', '\\PythonProject\\TestPython\\test.py')
获取路径与文件名以及将路径与文件名合并成带路径文件名
- basename()
获取文件名
- dirname()
获取路径
- join()
将路径和文件名合并成带路径文件名
import os.path
cur_path = r'D:\PythonProject\TestPython\test.py'
dir_name = os.path.dirname(cur_path)
base_name = os.path.basename(cur_path)
print(dir_name)
print(base_name)
print(os.path.join(dir_name, base_name))
D:\PythonProject\TestPython
test.py
D:\PythonProject\TestPython\test.py
获取绝对路径
absdir() 根据相对路径获取绝对路径
import os.path
print(os.path.abspath('.')) # 当前路径为D:\PythonProject\TestPython
D:\PythonProject\TestPython
获取文件时间相关数据(时间戳)
getctime() 获取文件创建时间(create)
getatime() 获取文件访问时间(access)
getmtime() 获取文件修改时间(modify)
import os.path
dest_file = r'.\test.py'
print(os.path.getctime(dest_file))
print(os.path.getatime(dest_file))
print(os.path.getmtime(dest_file))
1619794397.6112342
1619794924.8248465
1619794915.2267303
判断是否是文件、是否是路径、是否存在
- exsits() #
文件或目录实际是否存在
- isfile() #
是否是文件 前提是exisits()为True
- isdir() #
是否是目录 前提是exisits()为True
import os.path
dest_file = r'D:\PythonProject\TestPython\test.py' # 实际存在
dest_fake_file = r'C:\PythonProject\TestPython\test.py'# 实际不存在
dest_dir = r'D:\PythonProject\TestPython' # 实际存在
dest_fake_dir = r'C:\PythonProject\TestPython' # 实际不存在
dest_data = [dest_file, dest_fake_file, dest_dir, dest_fake_dir]
for one_data in dest_data:
print(f'{one_data}')
print('is file: {}'.format(os.path.isfile(one_data)))
print('is dir: {}'.format(os.path.isdir(one_data)))
print('is exsit:{}'.format(os.path.exists(one_data)))
D:\PythonProject\TestPython\test.py
is file: True
is dir: False
is exsit:True
C:\PythonProject\TestPython\test.py
is file: False
is dir: False
is exsit:False
D:\PythonProject\TestPython
is file: False
is dir: True
is exsit:True
C:\PythonProject\TestPython
is file: False
is dir: False
is exsit:False