欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python之os模块

程序员文章站 2022-07-10 14:19:08
...
import os
path = r'/Users/wangyajuan/Downloads'
1、指定文件路径删除文件 os.remove(path)   #remove()方法用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError。os.remove(path) (path:路径)
2、指定修改文件名,被修改文件名 os.rename(src, dst)   #os.rename(src, dst) os.rename() 方法用于重命名文件或目录,从 src 到 dst,如果dst是一个存在的目录, 将抛出OSError。(src – 要修改的目录名,dst – 修改后的目录名)
3、创建文件目录 os.mkdir()    #os.mkdir() 方法用于以数字权限模式创建目录。默认的模式为 0777 (八进制)。os.mkdir(path[, mode])path -- 要创建的目录 mode -- 要为目录设置的权限数字模式(eg:os.mkdir( path, 0755 );)
4、创建父级目录 os.makedirs() #os.makedirs() 方法用于递归创建目录。像 mkdir(), 但创建的所有intermediate-level文件夹需要包含子目录。eg:  创建目录:path = "/tmp/home/monthly/daily"  os.makedirs( path, 0755 )
5、搜索指定目录的文件 a = os.listdir(path)    #os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序。 它不包括 '.' 和'..' 即使它在文件夹中。eg: 创建目录path = "/var/www/html/" dirs = os.listdir( path )
6、判断是否为目录 os.path.isdir()     #os.path.isdir()用于判断某一对象(需提供绝对路径)是否为目录
7、判断是否为文件 os.path.isfile()    #os.path.isdir()用于判断某一对象(需提供绝对路径)是否为文件
8、进入指定路径(改变当前目录到指定的路径) os.chdir()          #os.chdir() 方法用于改变当前工作目录到指定的路径。os.chdir(path)
9、返回当前工作目录os.getcwd()   # os.getcwd() 获取当前路径
10、获取指定目录下所有文件
for cur_dir,dirs,files in os.walk(r'/学习/接口自动化/BestTest/摩羯座'):       # cur_dir(当前路径),dirs(目录),files(文件)中所有的
     print(cur_dir,dirs,files)
     print("=="*10)
11.name = '.mp4'
 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('/',name)
12、操作系统:
system只执行命令,不返回结果

os.system('ifconfig')
print(os.system('ifconfig'))

os.popen只执行命令,有返回结果
os.popen('ifconfig').read()
print("=====",os.popen('ifconfig').read()
 13、获取文件相关
os.path.getatime("name.txt")   #获取访问name.txt文件最近一次时间
os.path.getctime()             #获取name.txt文件创建时间
os.path.getmtime()             #获取name.txt文件修改时间
os.path.getsize(路径)              #获取name.txt文件大小
os.path.exists()               #可以直接判断文件/文件夹是否存在

14、获取文件名
#1、PATH指一个文件的全路径作为参数  2、如果给出的是一个目录和文件名,则输出路径和文件名 如果给出的是一个目录名,则输出路径和为空文件名
os.path.split()       #切片 os.path.split('PATH') os.path.split('C:/soft/python/test.py')   print:('C:/soft/python', 'test.py')

15、获取文件绝对路径
os.path.dirname('../')      #去掉文件名,返回目录 返回绝对路径
print(os.path.dirname('../BestTest/10.19/os模块.py')  )  结果:../BestTest/10.19/
os.path.abspath(__file__)  #获取当前.py 绝对路径           结果:绝对路径
print(os.path.abspath('../BestTest/10.19/'))    #(注:已当前路径获取绝对路径)        结果:绝对路径

16、删除目录
os.rmdir()          #删除空文件
os.removedirs()     #删除路径文件