一、os模块
1、os的文件与目录函数
函数名 | 参数 | 介绍 | 举例 | 返回值 |
getcwd | 无 | 返回当前的路径 | os.getcwd() | 字符串 |
listdir | path | 返回指定路径下所有的文件或文件夹 | os.listdir('c://abc') | 返回一个列表 |
makedirs | pathmode | 创建多级文件夹 | os.makedirs('d://abc/ab') | 无 |
removedirs | path | 删除多级文件夹 | os.removedirs('d://abc/ab') | 无 |
rename | Oldname Newname | 给文件或文件夹改名 | os.rename('d://abc',‘d://www’) | 无 |
rmdir | path | 只能删除空文件夹 | os.rmdir('d://abc') | 无 |
2、os.path模块常用方法
函数名 | 参数 | 介绍 | 举例 | 返回值 |
exists | path | 文件或路径是否存在 | os.path.exists('d://a') | bool |
isdir | path | 是否是路径 | os.path.isdir("d://") | bool |
isabs | path | 是否为绝对路径 | os.path.isabs('test') | bool |
isfile | path | 是否为文件 | os.path.isfile('d://a.txt') | bool |
join | path,path* | 路径字符串合并 | os.path.join('d://','test') | 字符串 |
split | path | 以最后一层路径为基准切割 | os.path.split('d://test') | 列表 |
以上方法相关的测试代码如下
# coding:utf-8
import os
import os.path
current_path = os.getcwd()
print(current_path)
print(os.path.isabs(current_path))
print(os.path.isabs('abc'))
new_path = '%s/test1' % current_path
if os.path.exists(new_path):
os.makedirs(new_path)
data = os.listdir(current_path)
print(data)
new_path1 = os.path.join(current_path, 'test1', 'abc')
print(new_path1)
if os.path.exists(new_path1):
os.makedirs(new_path1)
if os.path.exists('test2'):
os.makedirs('test2')
if os.path.exists('test1/abc'):
os.removedirs('test1/abc')
if os.path.exists('test2'):
os.rename('test2', 'test2_new')
if os.path.exists('demo1.py'):
os.rename('demo1.py', 'demo2.py')
if os.path.exists('%s/test1_new' % current_path):
os.rmdir('%s/test1_new' % current_path)
if os.path.exists('test1'):
os.rmdir('test1')
path1=os.path.join(current_path,'123')
print(path1)
os.mkdir(path1)
current_path = current_path + '/package_os.py'
print(os.path.isfile(current_path))
print(os.path.split(current_path))
print(os.path.isdir(os.path.split(current_path)[0]))
print(dir(os.path))