常用内置模块_os

烈酒焚心 提交于 2019-12-01 23:55:22

os用于执行操作系统命令

 

常用的方法:

os.getcwd() #获取当前路径os.system('ifconfig')# 执行操作系统命令;只执行命令,但是拿不到命令结果os.popen('ifconfig').read() #可以拿到所执行命令结果os.path.dirname(r'E:\case\login\a.mp3')  #获取a.mps的父目录os.path.abspath(__file__)   #根据相对路径获取绝对路径,__file__是获取当前文件绝对路径os.path.getsize('a.mp3') #获取大小os.path.exists()  #判断文件夹是否存在os.path.getatime()  #获取文件的最近一次访问时间os.path.getctime()  #获取文件的创建时间os.path.getmtime()  #获取文件的修改时间print(os.path.split(r'E:\case\login\a.mp3'))  #把文件路径和文件名分开os.removedirs() #删空文件夹os.rmdir()  #只能删除空文件夹
os.remove()  #移除os.rename()  #重命名os.mkdir('case') #创建单层目录文件夹os.makedirs('case/login')  #创建多层目录文件夹os.listdir(r'e:/home/xx/xxx')  #获取某一个目录下文件os.walk()  #遍历一个目录内各个子目录和子文件

os.walk()

for cur_dir,dirs,files in os.walk('E:\home\day'):    print(cur_dir,dirs,files)     #    print('==============')name = '.mp3'for cur_dir,dirs,files in os.walk('E:\home\day'):    for file in files:        if name in file:            abs_path = os.path.join(cur_dir,file) #找到的文件的绝对路径            print('找到%s文件,路径是%s'%(file,abs_path))写成一个找路径的函数def search_file(path,name):    for cur_dir, dirs, files in os.walk(path):        for file in files:            if name in file:                abs_path = os.path.join(cur_dir, file)  # 拼接路径,找到的文件的绝对路径                print('找到%s文件,路径是%s' % (file, abs_path))search_file('/home','.mp3') #查找home目录下所有.mP3的文件

 

 

 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!