Python之os模块学习介绍

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/laozhuxinlu/article/details/70787878

Python之os模块学习介绍


    Python的用处其实是很多的,有些人拿来做后台服务器,有些人做前端开发,还有一部分的人选择python去开发脚本工具。那么在这我想说的是,如果是用python去开发脚本工具,os模块的使用就相当重要了。

    特别是其中涉及到的文件/路径/字符串等操作……


1. 执行终端命令:  os.system(command)

    举例说,想在脚本环境下去执行命令:source test.sh (Linux环境下执行test.sh 这个shell脚本)

import os
command = source test.sh
os.system(command)

2. 删除文件 : os.remove(file)

    举例说,脚本执行删掉文件 /local/test/a.txt

扫描二维码关注公众号,回复: 3871946 查看本文章
import os
os.remove("/local/test/a.txt")

针对os.remove的使用,这边结合glob.glob模块(返回所有匹配的路径列表)批量删除文件

import os
import glob
files = /local/test/*txt
for deletefiles in glob.glob(files)
    os.remove(deletefiles)

3. 路径拼凑: os.path.join(pathStr,fileName)

    举例说,已知文件根目录和文件名得到文件完整路径

import os
pathStr=/local/test/file
fileName=text.txt
fullPath=os.path.join(pathStr, fileName)  //fullPath = /local/text/file/text.txt

4. 路径拆分:os.path.split(fullPath)

    举例说,已知text.txt文件的全路径,获取其根路径和文件名

import os
fullPath = /local/text/file/text.txt
detailPath = os.path.split(fullPath)
print detailPath    // detailPath = ('/local/text/file', 'text.txt')


5.  判定路径是否存在:os.path.exists(path)

    顾名思义

import os
pathName = /local/path/test
ifExist = os.path.exists(pathName)  // if exist, ifExist = true, else false

    Python下的os模块功能还是很强大的,这里只是举例说明了一些常见功能函数的使用。并且欢迎大家补充……


  

猜你喜欢

转载自blog.csdn.net/laozhuxinlu/article/details/70787878
今日推荐