博客
关于我
Python库os使用笔记
阅读量:222 次
发布时间:2019-03-01

本文共 1159 字,大约阅读时间需要 3 分钟。

文件目录相关

基础函数

以下是一些常用的文件和目录操作函数:

# 路径存在os.path.exists(path)  # 路径是目录os.path.isdir(path)  # 删除目录os.remove(path)  # 列出path目录下的所有文件(含文件夹)os.listdir(path)  # 切分文件名里面的基础名称和后缀部分os.path.splitext(filename)  # 组合需要操作的文件名为绝对路径os.path.join(path,filename)  # 重命名某个文件os.rename(filename)  # 从绝对路径中获取最后的文件名print(os.path.basename)  # 创建文件夹os.mkdir(dirpath)

目录不存在时创建它

检查目录是否存在后创建:

if not os.path.exists(dirpath):      os.mkdir(dirpath)

遍历目录下的所有路径

一次性获取所有文件和目录:

for root, dirs, files in os.walk(path):      # root 表示当前正在访问的文件夹路径      # dirs 表示该文件夹下的子目录名list      # files 表示该文件夹下的文件list      # 遍历文件      for name in files:          file_path = os.path.join(root, name)      # 遍历所有的文件夹      for name in dirs:          folder_path = os.path.join(root, name)

只能遍历目录下的文件,可以获取文件名和文件路径:

for file in os.scandir(path):      print(file.name, file.path)

只能获取文件名,不能获取路径:

for file in os.listdir(path):      print(file)

目录获取

获取当前工作目录和脚本所在目录:

import os  # 获取工作目录  os.getcwd()  # 获取脚本所在的目录  os.path.split(os.path.realpath(__file__))[0]  # 也可以使用sys模块来获取  sys.path[0]

系统相关

执行系统命令

使用os模块执行系统命令:

import os  os.system('cd /usr/local')  os.mkdir('aaa.txt')  os.system('cd /usr/local && mkdir aaa.txt')

转载地址:http://wkwt.baihongyu.com/

你可能感兴趣的文章
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install 权限问题
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>