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 模块常用操作的更多相关文章

  1. python OS 模块 文件目录操作

    Python OS 模块 文件目录操作 os模块中包含了一系列文件操作的函数,这里介绍的是一些在Linux平台上应用的文件操作函数.由于Linux是C写的,低层的libc库和系统调用的接口都是C AP ...

  2. Python OS模块常用功能 中文图文详解

    一.Python OS模块介绍 OS模块简单的来说它是一个Python的系统编程的操作模块,可以处理文件和目录这些我们日常手动需要做的操作. 可以查看OS模块的帮助文档: >>> i ...

  3. python os模块 常用命令

    python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...

  4. python os模块常用命令

    python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...

  5. [转]python os模块 常用命令

    python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...

  6. Python OS模块常用函数说明

    Python的标准库中的os模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的.即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Wi ...

  7. python os模块 文件操作

    Python内置的os模块可以通过调用操作系统提供的接口函数来对文件和目录进行操作 os模块的基本功能: >>> import os >>> os.name 'po ...

  8. Python os模块常用部分功能

    os.sep 可以取代操作系统特定的路径分割符. os.name字符串指示你正在使用的平台.比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'. os.getcw ...

  9. Python OS模块常用

    python 读写.创建 文件 第二个:目录操作-增删改查 第三个:判断 第四个:PATH 第四个:os.mknod 创建文件(不是目录) import os os.chdir("/&quo ...

随机推荐

  1. Python爬虫:HTTP协议、Requests库(爬虫学习第一天)

    HTTP协议: HTTP(Hypertext Transfer Protocol):即超文本传输协议.URL是通过HTTP协议存取资源的Internet路径,一个URL对应一个数据资源. HTTP协议 ...

  2. 【剑指Offer】9、变态跳台阶

      题目描述:   一只青蛙一次可以跳上1级台阶,也可以跳上2级--它也可以跳上n级.求该青蛙跳上一个n级的台阶总共有多少种跳法.   解题思路:   当只有一级台阶时,f(1)=1:当有两级台阶时, ...

  3. 05-Linux系统编程-第02天(文件系统、目录操作、dup2)

    1 课程回顾 02-文件存储 文件名不在inode里 而是保存在一个叫dentry的结构体里了 格式化就是指定一组规则 指定对文件的存储及读取的一般方法 linux下主要使用 ext2 ext3 ex ...

  4. 洛谷P1996 约瑟夫问题【队列】

    题目背景 约瑟夫是一个无聊的人!!! 题目描述 n个人(n<=100)围成一圈,从第一个人开始报数,数到m的人出列,再由下一个人重新从1开始报数,数到m的人再出圈,--依次类推,直到所有的人都出 ...

  5. 05.Python高级编程

    1 ==,is的使用 is 是比较两个引用是否指向了同一个对象(地址引用比较). == 是比较两个对象是否相等.(比较的数值) 2 深拷贝.浅拷贝.copy.copy 2.1 浅拷贝 浅拷贝: 拷贝的 ...

  6. python中的二进制、八进制、十六进制

    python中通常显示和运算的是十进制数字. 一.python中的二进制 bin()函数,将十进制转换为二进制,0b是二进制的前缀.如: >>> bin(10) '0b1010' 二 ...

  7. Python 实现 Excel 里单元格的读写与清空操作

    #coding=utf-8 # coding=utf-8 作用是声明python代码的文本格式是utf-8,python按照utf-8的方式来读取程序. # 如果不加这个声明,无论代码中还是注释中有中 ...

  8. cannot find -lGL

    解决方法: 以下操作都在root权限下进行! 1.按照提示安装对应的库文件,fedora安装库件的格式:yum install libxxx(你要装的库),如果已经安装GL库,会显示已经安装 Ps:如 ...

  9. @Transactional 注解的使用和注意

    转载:http://epine.itpub.net/post/8159/526281 1. 在需要事务管理的地方加@Transactional 注解.@Transactional 注解可以被应用于接口 ...

  10. javascript学习笔记(一)-廖雪峰教程

    一. 基础 1.for in,for of和forEach 遍历的是对象的属性,因为数组也是对象,其内部的元素的索引就是其属性值.用该方式遍历数组就是获取了数组中的每一个元素的索引值(从0開始). 而 ...