基于Python os模块常用命令介绍

yipeiwu_com6年前Python基础

1、os.name---判断现在正在实用的平台,Windows返回'nt';linux返回'posix'

2、os.getcwd()---得到当前工作的目录。

3、os.listdir()---

4、os.remove---删除指定文件

5、os.rmdir()---删除指定目录

6、os.mkdir()---创建目录(只能创建一层)

7、os.path.isfile()---判断指定对象是否为文件。是则返回True。

8、os.path.isdir()---判断指定对象是否为目录

9、os.path.exists()---判断指定对象是否存在。

10、os.path.split()---返回目录的目录和文件名。

11、os.path.join(path, name)——连接目录和文件名。

++++++++++++++++++++++++++++++++++++++++++++

import os

os_path = '/home/meringue/Documents/PythonFile/osNotes/'
## 更改当前工作目录
os.chdir(os_path)
## 获取当前工作目录
os.getcwd()

'/home/meringue/Documents/PythonFile/osNotes'

## 返回当前系统(windows: nt; Linux: posix) 
os.name

'posix'

## 创建文件和文件目录
for i in range(5):
  os.mknod('test_file'+str(i)+'.txt') # 文件
  os.mkdir('test_docu'+str(i)) # 文件目录
os.makedirs('./test_docu5/test_docu0/') # 多层文件夹路径1
## 获取指定路径下的文件列表(不区分文件和文件夹)
os.listdir(os_path)

['.ipynb_checkpoints',
 'test_docu2',
 'test_docu1',
 'test_docu3',
 'test_file2.txt',
 'test_docu4',
 'test_docu5',
 'osNotes.ipynb',
 'test_file3.txt',
 'test_docu0',
 'test_file0.txt',
 'test_file4.txt',
 'test_file1.txt']

## 删除当前目录下指定文件或文件夹
os.remove('./test_file0.txt') # 文件
os.rmdir('./test_docu0/') # 文件夹

## 判断指定对象是否为文件或目录(返回True或False)
print os.path.isfile('./test_file1.txt')
print os.path.isdir('./test_docu5/test_docu0/')

True
True

## 判断指定对象是否存在(两个对象均已在上述步骤中被删除)
print os.path.exists('./test_file0.txt')
print os.path.exists('./test_docu0/')

False
False

## 返回路径的目录和文件名
print os.path.split(os_path)
print os.path.split(os_path+'test_file1.txt')

('/home/meringue/Documents/PythonFile/osNotes', '')
('/home/meringue/Documents/PythonFile/osNotes', 'test_file1.txt')

## 返回绝对路径
print os.path.abspath('./test_file1.txt')
print os.path.abspath('./test_docu1/')

/home/meringue/Documents/PythonFile/osNotes/test_file1.txt
/home/meringue/Documents/PythonFile/osNotes/test_docu1

## 连接目录和文件名
os.path.join(os_path,'test_file1.txt')

'/home/meringue/Documents/PythonFile/osNotes/test_file1.txt'

## 返回文件名和文件路径
print os.path.basename(os_path+'test_file1.txt')
print os.path.dirname(os_path+'test_file1.txt')

test_file1.txt
/home/meringue/Documents/PythonFile/osNotes

以上这篇基于Python os模块常用命令介绍就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python内存读写操作示例

Python内存读写操作示例

本文实例讲述了Python内存读写操作。分享给大家供大家参考,具体如下: Python中的读写不一定只是文件,还有可能是内存,所以下面实在内存中的读写操作 示例1: # -*- co...

使用TensorFlow-Slim进行图像分类的实现

参考 https://github.com/tensorflow/models/tree/master/slim 使用TensorFlow-Slim进行图像分类 准备 安装Tensor...

Python设计模式之组合模式原理与用法实例分析

Python设计模式之组合模式原理与用法实例分析

本文实例讲述了Python设计模式之组合模式原理与用法。分享给大家供大家参考,具体如下: 组合模式(Composite Pattern):将对象组合成成树形结构以表示“部分-整体”的层次...

Python验证企业工商注册码

中国企业工商注册码前六位为行政区代码,中间8位顺序编码,最后一位为根据ISO 7064:1983.MOD 11-2校验码计算出来的检验码,本算法根据最后一位校验码的算法来判断企业注册码是...

django 捕获异常和日志系统过程详解

这一块的内容很少, 异常使用try except即可, 日志只需要几行配置. 使用装饰器捕获方法内的所有异常 我使用装饰器来整个包裹一个方法, 捕获方法中的所有异常信息.并将其转为j...