python的os函数

import os

1.rename文件从重命名

第一个参数是原文件名,第二个参数是新文件名。
os.rename('file/a.txt','aa.txt')

2.remove删除文件

os.remove('file/file02')

3.创建目录(只能创建一层目录)

os.mkdir('file02')

4.创建多层目录

os.makedirs('file04/file05',exist_ok=True)#exist_ok不用报错

5.rmdir()删除空目录(删除一层空目录)

os.rmdir('file02')

6.removedirs() 删除多层目录

os.removedirs('file04/file05')

7.getcwd() 获取当前文件所在目录

ret=os.getcwd()
print(ret)#D:\pythonworkspace

8.listdir获取目录列表

ret=os.listdir(os.getcwd())
print(ret)

9.切换所在目录chdir()

os.chdir(os.getcwd()+'/file')
print(os.getcwd())

10.判断文件或文件夹是否存在

ret=os.path.exists('aa.txt')
print(ret)

11.判断是否为文件

ret=os.path.isfile('aa,txt')
print(ret)

12.判断是否为目录

ret=os.path.isdir('aa.txt')
print(ret)

13.获取绝对路径

ret=os.ppath.abspath('file')
print(ret)#D:\pythonworksace\file

14.判断是否为绝对路径

ret1=os.path.abspath('file')
ret1=os.getcwd()
print(ret1)
ret=os.path.isabs(ret1)
print(ret)

15.获取路径中的最后部分

ret=os.path.basename('file04/file05/a')
print(ret)

16.获取路径中的路径部分

print(os.getcwd())
ret=os.path.dirname(os.getcwd())#dirname获取上一路径
print(ret)

17.将多个目录组织成路径返回

ret=os.path.join('aa','bb','cc')
print(ret)

18.获取文件信息

getatime()返回path所指向的文件或者目录的最后访问时间
getctime()查看文件创建时间
getmtime()返回path所指向的文件或者目录的最后修改时间
getsize()查看文件的大小
ret=os.path.getsize('file')
print(ret)

猜你喜欢

转载自blog.csdn.net/weixin_44239431/article/details/86249490