Python之os库的使用

1. os库基本介绍

os库提供通用的、基本的操作系统交互功能

image-20210228134214794

  • os 库是Python标准库,包含几百个函数
  • 常用路径操作、进程管理、环境参数等几类

详解介绍

  • 路径操作:os.path子库,处理文件路径及信息

  • 进程管理:启动系统中其他程序

  • 环境参数:获得系统软硬件信息等环境参数

2. os库之路径操作

os库使用os.path子库来进行路径操作,os.path子库以path为入口,用于操作和处理文件路径。这里的path指的是目录或包含文件名称的文件的路径

import os.path 或者 import os.path as op

路径操作

函数 描述 例子
os.path.abspath(path) 返回path在当前系统中的绝对路径 >>>os.path.abspath( "file.txt" ) 'C:\Users\Tian Song\Python36-32\file.txt'
os.path.normpath(path) 归一化path的表示形式,统一用\分隔路径 >>>os.path.normpath( "D://PYE//file.txt" ) 'D:\\PYE\\file.txt'
os.path.relpath(path) 返回当前程序与文件之间的相对路径 (relative path) >>>os.path.relpath( "C://PYE//file.txt" ) '..\..\..\..\..\..\..\PYE\file.txt'
os.path.dirname(path) 返回path中的目录名称 >>>os.path.dirname( "D://PYE//file.txt" ) 'D://PYE'
os.path.basename(path) 返回path中最后的文件名称 >>>os.path.basename( "D://PYE//file.txt" ) 'file.txt'
os.path.join(path, *paths) 组合path与paths,返回一个路径字符串 >>>os.path.join( "D:/", "PYE/file.txt" ) 'D:/PYE/file.txt'
os.path.exists(path) 判断path对应文件或目录是否存在,返回True或False >>>os.path.exists( "D://PYE//file.txt" ) False
os.path.isfile(path) 判断path所对应是否为已存在的文件,返回True或False >>>os.path.isfile( "D://PYE//file.txt" ) True
os.path.isdir(path) 判断path所对应是否为已存在的目录,返回True或False >>>os.path.isdir( "D://PYE//file.txt" ) False
os.path.getatime(path) 返回path对应文件或目录上一次的访问时间 >>>os.path.getatime( "D:/PYE/file.txt" ) 1518356633.7551725
os.path.getmtime(path) 返回path对应文件或目录最近一次的修改时间 >>>os.path.getmtime( "D:/PYE/file.txt" ) 1518356633.7551725
os.path.getctime(path) 返回path对应文件或目录的创建时间 >>time.ctime(os.path.getctime( "D:/PYE/file.txt" )) 'Sun Feb 11 21:43:53 2018'
os.path.getsize(path) 返回path对应文件的大小,以字节为单位 >>>os.path.getsize( "D:/PYE/file.txt" ) 180768
os.path.abspath(path)
os.path.normpath(path)
os.path.relpath(path)
os.path.dirname(path)
os.path.basename(path)
os.path.join(path)
os.path.exists(path)
os.path.isfile(path)
os.path.isdir(path)
os.path.getatime(path)
os.path.getmtime(path)
os.path.getctime(path)
os.path.getsize(path)

3. os库的进程管理

进程管理指的是使用我们编写的python程序,去调用其他的外部程序。那么os库提供了—个函数叫system,它够执行复它的程序或命令。

os.system(command)
  • 执行程序或命令command
  • 在Windows系统中,返回值为cmd的调用返回信息

例子:使用 os.system 函数调用 Windows 下面的计算器程序

只需要将计算器程序的文件路径作为参数放到os.system函数中,执行该语句之后,计算器程序运行出来,同时本函数调用结束返回一个0,指的是程序正确运行

>>> import os
>>> os.system("C:\\Windows\\System32\\calc.exe")
0

我们也可以给调用的程序赋予相关的参数,比如调用windows操作系统中的 mspaint ,也就是画图程序,并且指定一个文件给这个画图程序让它默认打开。只需要使用画图程序 mspaintexe ,同时在后面通过空格给合出要打开的文件,作为参数给出 system函数就可以了。

>>> os.system("C:\\Windows\\System32\\mspaint.exe C:\\Users\\ASUS\\Desktop\\1.PNG")
0

注意要打开的程序和后面的参数之间只有一个空格,没有其他东西。


4. os库之环境参数

函数 描述 例子
os.chdir(path) 修改当前程序操作的路径 >>>os.chdir("D:")
os.getcwd() 返回程序的当前路径 >>>os.getcwd()
os.getlogin() 获得当前系统登录用户名称 >>>os.getlogin()
os.cpu_count() 获得当前系统的CPU数量 >>>os.cpu_count()
os.urandom(n) 获得n个字节长度的随机字符串,通常用于加解密运算 >>>os.urandom(10)
posted @ 2021-02-28 17:06  狸帅  阅读(1257)  评论(0编辑  收藏  举报