python os 模块常用操作
python 2.7 os 常用操作
官方document链接
文件和目录
- os.access(path, mode) 读写权限测试
应用:
try:
fp = open("myfile")
except IOError as e:
if e.errno == errno.EACCES:
return "some default data"
# Not a permission error.
raise
else:
with fp:
return fp.read()
模式说明:
os.F_OK
Value to pass as the mode parameter of access() to test the existence of path.
os.R_OK
Value to include in the mode parameter of access() to test the readability of path.
os.W_OK
Value to include in the mode parameter of access() to test the writability of path.
os.X_OK
Value to include in the mode parameter of access() to determine if path can be executed.
- os.chdir(path) 改变目录
- os.getcwd() 获取当前工作目录
- os.listdir(path) 列出目录中的文件,不包含'.' 和 '..'
- os.mkdir(path[, mode]) 创建单个目录,可以添加文件夹的读写属性
Create a directory named path with numeric mode mode. The default mode is 0777 (octal). If the directory already exists, OSError is raised
- os.makedirs(path[, mode]) 创建多级目录
- os.remove(path) 删除文件
Remove (delete) the file path. If path is a directory, OSError is raised; see rmdir() below to remove a directory. This is identical to the unlink() function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.
- os.removedirs(path) 删除多级目录
Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, os.removedirs('foo/bar/baz') will first remove the directory 'foo/bar/baz', and then remove 'foo/bar' and 'foo' if they are empty. Raises OSError if the leaf directory could not be successfully removed.
- os.rmdir(path) 删除目录,只有目录是空的时候,才有作用
Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised. In order to remove whole directory trees, shutil.rmtree() can be used.
- os.rename(src, dst) 文件重命名
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file.
- os.renames(old, new) 多级目录重命名
Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs().
系统操作
- os.system(command) 执行命令行操作
subprocess 可以提供更加强大的功能
On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.
On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation.
假如要执行多个命令,则需要在每个命令后加 '&'
应用:
>>> command = "cd D:\\LearnPython\\base & dir"
>>> os.system(command)
通用路径名操作 os.path
- os.path.abspath(path) 返回当前目录的绝对路径
- os.path.basename(path) 返回路径中的基础名
>>> os.path.basename('D:\\LearnPython\\base')
'base'
- os.path.dirname(path) 返回当前文件夹的上层路径名
>>> os.path.dirname('D:\\LearnPython\\base')
'D:\\LearnPython'
- os.path.exists(path) 检查路径是否存在,可用于检查目录或文件是否存在
>>> os.path.exists('D:\\LearnPython\\base')
True
>>> os.path.exists('D:\\LearnPython\\base\\wrn_log.py')
True
>>> os.path.exists('D:\\LearnPython\\base\\wrn_log.pyy')
False
- os.path.getsize(path) 获取文件大小,单位bytes
>>> os.path.getsize('D:\\LearnPython\\base\\wrn_log.py')
1307L
os.path.isabs(path) 判断是否是绝对路径
os.path.isfile(path) 判断path中的是否是一个已经存在的文件
os.path.isdir(path) 判断是否为一个已经存在的目录
os.path.join(path, *paths) 对目录路径进行拼接
Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.
应用:
>>> p = os.path.join("d:\\", "LearnPython\\base")
>>> p
'd:\\LearnPython\\base'
- os.path.split(path) 对路径进行分割,返回一个tuple(head, tail),和join可以对应
>>> s = os.path.split("d:\\LearnPython\\base")
>>> s
('d:\\LearnPython', 'base')
- os.path.splitdirve(path) 对路径进行分割,但可以分离出驱动盘
>>> s = os.path.splitdrive("d:\\LearnPython\\base")
>>> s
('d:', '\\LearnPython\\base')
- os.path.splitext(path) 分割扩展名
>>> s = os.path.splitext("d:\\LearnPython\\base\\wrn_log.py")
>>> s
('d:\\LearnPython\\base\\wrn_log', '.py')
- os.path.walk(path, visit, arg) 获取目录树。在Py3中已经改为os.walk()
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print root, "consumes",
print sum(getsize(join(root, name)) for name in files),
print "bytes in", len(files), "non-directory files"
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
python os 模块常用操作的更多相关文章
- python OS 模块 文件目录操作
Python OS 模块 文件目录操作 os模块中包含了一系列文件操作的函数,这里介绍的是一些在Linux平台上应用的文件操作函数.由于Linux是C写的,低层的libc库和系统调用的接口都是C AP ...
- Python OS模块常用功能 中文图文详解
一.Python OS模块介绍 OS模块简单的来说它是一个Python的系统编程的操作模块,可以处理文件和目录这些我们日常手动需要做的操作. 可以查看OS模块的帮助文档: >>> i ...
- python os模块 常用命令
python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...
- python os模块常用命令
python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...
- [转]python os模块 常用命令
python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...
- Python OS模块常用函数说明
Python的标准库中的os模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的.即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Wi ...
- python os模块 文件操作
Python内置的os模块可以通过调用操作系统提供的接口函数来对文件和目录进行操作 os模块的基本功能: >>> import os >>> os.name 'po ...
- Python os模块常用部分功能
os.sep 可以取代操作系统特定的路径分割符. os.name字符串指示你正在使用的平台.比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'. os.getcw ...
- Python OS模块常用
python 读写.创建 文件 第二个:目录操作-增删改查 第三个:判断 第四个:PATH 第四个:os.mknod 创建文件(不是目录) import os os.chdir("/&quo ...
随机推荐
- Leetcode刷题笔记——查找
33.Search in Rotated Sorted Array 题目描述: 给定一个被翻转的整型升序数组nums,数组中无重复元素,如[4,5,6,7,0,1,2],和一个整数target.要求在 ...
- Html 页面刷新后出现闪动
Html 页面刷新后,或跳转后,出现闪动,抖动问题 1.查看有没有用到新字体,新字体链接位置是否存在 如: @font-face { font-family: "AvantGarde-Dem ...
- Appium的ios配置
automationName text XCUITest platformName text iOS platformVersion ...
- UVA489 - Hangman Judge【紫书例题4.2】
题意:就是给出一个字符串,让你去一个一个猜测,相同字母算一次,如果是之前猜过的也算错,如果你在错7次前猜对就算你赢,文章中是LRJ的例题代码. #include<stdio.h> #inc ...
- 爬虫系列(二) Chrome抓包分析
在这篇文章中,我们将尝试使用直观的网页分析工具(Chrome 开发者工具)对网页进行抓包分析,更加深入的了解网络爬虫的本质与内涵 1.测试环境 浏览器:Chrome 浏览器 浏览器版本:67.0.33 ...
- OO第四单元总结——查询UML类图 暨 OO课程总结
一.本单元两次作业的架构设计总结 作业一.UML类图查询 1. 统计信息图 2. 复杂度分析 基本复杂度(Essential Complexity (ev(G)).模块设计复杂度(Module Des ...
- 【例题4-6 uva12412】A Typical Homework (a.k.a Shi Xiong Bang Bang Mang)
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 训练编程的题. 原题中没有除0的数据,所以别担心你的代码是因为除0错了. 多半跟我一样. 也是因为没有+eps 就是比如你要算tot ...
- PHP学习总结(13)——PHP入门篇之常量
1.什么是常量 什么是常量?常量可以理解为值不变的量(如圆周率):或者是常量值被定义后,在脚本的其他任何地方都不可以被改变.PHP中的常量分为自定义常量和系统常量(后续小节会详细介绍). 自定义常量是 ...
- i=i+1,i+=1与i++的区别
1. i=i+1 a.读取右i的地址 b,i=1 c.读取左i的地址 d. 值赋给左i 2.i+=1 a.读取左i的地址 b.i+1 c.值给i 3.i++ a.读取右i的地址 b.值加1
- HDU 3691
一个源点,一个汇点,明显是网络流的问题,但据说用网络流来求最小割,会超时..囧,那出题的人是怎么想的... 用SW的算法来求最小割. #include <iostream> #includ ...