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 ...
随机推荐
- Vuex教程简单实例
什么是Vuex? vuex是一个专门为vue.js设计的集中式状态管理架构.状态?我把它理解为在data中的属性需要共享给其他vue组件使用的部分,就叫做状态.简单的说就是data中需要共用的属性. ...
- BZOJ 4712: 洪水 挖坑待补
Code: #include<bits/stdc++.h> #define setIO(s) freopen(s".in","r",stdin) # ...
- 01-Linux命令基础-第01天(命令基础,软件安装与卸载、磁盘管理)
01- Linux初步 最早一直是单道程序设计模型的操作系统 69年贝尔实验室决定开发多道程序设计模型的操作系统 Multics计划 (失败了) x86 IA(Intel Architecture ...
- [置顶]
我的 Java 后端书架 (2016 年暖冬版)
转自: http://calvin1978.blogcn.com/articles/bookshelf16.html 我的 Java 后端书架 (2016 年暖冬版) 本书架主要针对 Java 后端 ...
- 绝对好用的浏览器json解析网址
你们是否经常在浏览器输入请求地址解析遇到中文乱码的情况,今天我找到了一个好用的浏览器解析json网址,绝对好用. 1.直接输入网址 http://pro.jsonlint.com/ 2.输入要解析的j ...
- Proc、宿主变量、指示变量、数组变量、通信区sqlca,oraca ---(day07)
PROC 主要内容: ) proc简介 ) proc程序的开发过程 ) 宿主变量和指示变量 ) 嵌入sql语句 ) 连接数据库 ) 错误处理 ) 数据的存取更新操作 ) 动态sql --------- ...
- [51Nod 1218] 最长递增子序列 V2 (LIS)
传送门 Description 数组A包含N个整数.设S为A的子序列且S中的元素是递增的,则S为A的递增子序列.如果S的长度是所有递增子序列中最长的,则称S为A的最长递增子序列(LIS).A的LIS可 ...
- shell脚本中source无效
发现在shell里面执行source,提示找不到命令.所以,我取搜了一些资料,总结一下. 一. 脚本中,source找不到命令--------------是因为用了sh执行脚本,而debian系统的s ...
- 11、mybatis的映射xml中参数类型的别名
在mapper.xml中,定义很多的statement,statement需要parameterType指定输入参数的类型.需要resultType指定输出结果的映射类型. 如果在指定类型时输入类型全 ...
- Nikita and stack
Nikita and stack time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...