Python必学的os模块

操作
1.获取平台信息

2.对目录的操作

3.判断操作

获取平台信息
os.name

获取正在使用的工作平台
os.getcwd() 获得当前工作目录的路径
os.getenv(环境变量名称) 读取环境变量
对目录的操作
os.listdir()

返回指定目录下的所有目录和文件
os.mkdir() 创建一个目录
os.rmdir() 删除一个空目录,若目录中有文件无法删除
os.chdir() 改变当前目录到指定目录
os.rename() 重命名目录或文件
判断操作
os.path.exists(path)

判断文件或目录是否存在,存在则返回True,否则返回False
os.path.isfile(path) 判断是否为文件
os.path.isdir(path) 判断是否为目录
path模块
os.path.join(path,name)

将目录和文件拼接
os.path.getmtime() 获取文件的末次修改时间
os.path.abspath() 获取绝对路径
实例

  1. Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900
    64 bit (AMD64)] on win32 Type “help”, “copyright”, “credits” or
    “license” for more information.

    import os
    os.name ‘nt’
    os.getcwd
    os.getcwd() ‘C:\Users\king\AppData\Local\Programs\Python\Python36’
    os.mkdir(‘a’)
    os.path.exists(‘a’) True
    os.path.exists(‘b’) False
    os.path.isfile(‘a’) False
    os.path.isdir(‘a’) True
    os.path.getctime(‘a’)
    1552643015.653628

    os.listdir(os.getpwd()) Traceback (most recent call last): File “”, line 1, in AttributeError: module ‘os’ has
    no attribute ‘getpwd’

    os.listdir(os.getcwd()) [‘a’, ‘chromedriver.exe’, ‘cx_Oracle-doc’, ‘DLLs’, ‘Doc’, ‘geckodriver.exe’,
    ‘IEDriverServer.exe’, ‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’,
    ‘NEWS.txt’, ‘python.exe’, ‘python3.dll’, ‘python36.dll’,
    ‘pythonw.exe’, ‘Scripts’, ‘selenium’, ‘tcl’, ‘Tools’,
    ‘vcruntime140.dll’]

    os.path.abspath(‘a’) ‘C:\Users\king\AppData\Local\Programs\Python\Python36\a’
    os.rmdir(‘a’)
    os.listdir(os.getcwd()) [‘chromedriver.exe’, ‘cx_Oracle-doc’, ‘DLLs’, ‘Doc’, ‘geckodriver.exe’, ‘IEDriverServer.exe’, ‘include’,
    ‘Lib’, ‘libs’, ‘LICENSE.txt’, ‘NEWS.txt’, ‘python.exe’,
    ‘python3.dll’, ‘python36.dll’, ‘pythonw.exe’, ‘Scripts’, ‘selenium’,
    ‘tcl’, ‘Tools’, ‘vcruntime140.dll’]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值