首页 > 编程 > Python > 正文

Python OS模块实例详解

2019-11-25 13:01:20
字体:
来源:转载
供稿:网友

本文实例讲述了Python OS模块。分享给大家供大家参考,具体如下:

os模块

在自动化测试中,经常需要查找操作文件,比如查找配置文件(从而读取配置文件的信息),查找测试报告等等,经常会对大量文件和路径进行操作,这就需要依赖os模块。

1. os.getcwd()

功能:查看当前所在路径

import osprint(os.getcwd())

2. os.listdir()

列举目录下所有的文件,返回的是列表类型

import osprint(os.listdir("c:/file"))

3. os.path.abspath(path)

功能:返回path的绝对路径

绝对路径:【路径具体的写法】”D:/Learn/python/day15”

相对路径:【路径的简写】 :”.”

import osprint(os.path.abspath("."))

4. os.path.split(path)

功能: 将路径分解为(文件夹,文件名),返回的是元组类型

注意:若路径字符串最后一个字符是,则只有文件夹部分有值,若路径字符串中均无,则只有文件名部分有值,若路径字符串有/且不在最后,则文件夹和文件名都有值,且返回的结果不包括/

import osprint(os.path.split(r"D:/python/file/hello.py"))

结果:

('D:/python/file','hello.py')

print(os.path.split("."))

结果:

('','.')

os.path.split('D://pythontest//ostest//')

结果:

('D://pythontest//ostest', '')

5. os.path.join(path1,path2,…)

将path进行组合,若其中有绝对路径,则之前的path将会被删除.

>>> import os>>> os.path.join(r"d:/python/test",'hello.py')'d:/pyhton/test/hello.py'>>> os.path.join(r"d:/pyhton/test/hello.py",r"d:/pyhton/test/hello2.py")'d:/pyhton/test/hello2.py'

6. os.path.dirname(path)

返回path中文件夹部分,不包括”/”

>>> import os>>> os.path.dirname(r"d:/pyhton/test/hello.py")'d:/pyhton/test'>>> os.path.dirname(".")''>>> os.path.dirname(r"d:/pyhton/test/")'d:/pyhton/test'>>> os.path.dirname(r"d:/pyhton/test")test

7. os.path.basename(path)

功能:返回path中的文件名

>>> import os>>> os.path.basename(r"d:/pyhton/test/hello.py")'hello.py'>>> os.path.basename(".")'.'>>> os.path.basename(r"d:/pyhton/test/")''>>> os.path.basename(r"d:/pyhton/test")'test'

8. os.path.getsize(path)

功能: 获取文件的大小,若是文件夹则返回0

>>> import os>>> os.path.getsize(r"d:/pyhton/test/hello.py")38L>>> os.path.getsize(r"d:/pyhton/test")0L

9. os.path.exists(path)

功能:判断文件是否存在,若存在返回True,否则返回False

>>> import os>>> os.listdir(os.getcwd())['hello.py','test.txt']>>> os.path.exists(r"d:/python/test/hello.py")True>>> os.path.exists(r"d:/python/test/hello1.py")False

10.os.path.isdir(path)

功能:判断该路径是否为目录

>>> import os>>>os.path.isdir(r"C:/Users/zhangjiao/PycharmProjects/day01")True>>>os.path.isdir(r"C:/Users/zhangjiao/PycharmProjects/day01/hello.py")False

11.os.path.isfile(path)

功能:判断该路径是否为文件

import osprint(os.path.isfile(r'C:/360用户文件'))print(os.path.isfile(r'C:/core.dmp'))

输出:

False
True

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表