编程语言
首页 > 编程语言> > Python os.path模块

Python os.path模块

作者:互联网

os.path主要对文件、文件夹进行处理,常用的函数可以分为四类:

解析路径

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')

获取路径与文件名以及将路径与文件名合并成带路径文件名

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

判断是否是文件、是否是路径、是否存在

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

标签:PythonProject,Python,print,dest,TestPython,path,os
来源: https://blog.csdn.net/xp178171640/article/details/116310222