目录
- os的文件与目录函数介绍
- os.path模块常用函数介绍
os的文件与目录函数介绍
os.path模块常用方法
实战
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/8/21 20:41
# @Author : InsaneLoafer
# @File : package_os.py
import os
current_path = os.getcwd()
print(current_path)
print(os.path.isabs(current_path))
print(os.path.isabs('animal')) # 判断是否为绝对路径
new_path = os.path.join(current_path, 'test2', 'abc')
if os.path.exists(new_path):
os.removedirs(new_path)
else:
os.makedirs(new_path)
data = os.listdir(current_path)
print(data)
new_path2 = '%s/test2/abc' % current_path # 创建多级目录
if os.path.exists(new_path2):
os.removedirs(new_path2)
else:
os.makedirs(new_path2)
if os.path.exists('test3'):
os.removedirs('test3')
else:
os.makedirs('test3') # 以相对路径创建
if os.path.exists('test3'):
os.rename('test3', 'test3_new')
if os.path.exists('%s/test3_new' % current_path):
os.rmdir('%s/test3_new' % current_path) # 只能删除空目录
print(os.path.split(current_path))
current_path = current_path + '/package_os.py'
print(os.path.split(current_path)) # 分割最后一个文件
print(os.path.isfile(current_path)) # 判断是否为文件
print(os.path.isdir(current_path)) # 判断是否为目录
print(os.path.isdir(current_path[0]))
D:\My_Files\Python Project\pythonlean\python_package
True
False
['animal', 'package_datetime.py', 'package_os.py', 'package_time.py', 'test1', 'test2']
('D:\\My_Files\\Python Project\\pythonlean', 'python_package')
('D:\\My_Files\\Python Project\\pythonlean\\python_package', 'package_os.py')
True
False
False
Process finished with exit code 0