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. eas之常用源码整理

    //查看是否有相关权限 boolean hasAllotPermission=         PermissionFactory.getRemoteInstance().hasFunctionPer ...

  2. 拷贝构造和拷贝赋值、静态成员(static)、成员指针、操作符重载(day06)

    十七 拷贝构造和拷贝赋值 浅拷贝和深拷贝 )如果一个类中包含指针形式的成员变量,缺省的拷贝构造函数只是复制了指针变量的本身,而没有复制指针所指向的内容,这种拷贝方式称为浅拷贝. )浅拷贝将导致不同对象 ...

  3. vue 手机键盘把底部按钮顶上去

    背景:在写提交订单页面时候,底部按钮当我点击输入留言信息的时候,底部提交订单按钮被输入法软键盘顶上去遮挡住了. h5 ios输入框与键盘 兼容性优化 实现原理:当页面高度发生变化的时候改变底部butt ...

  4. jupyter记事本的安装和简单应用

    1.概述 jupyter记事本是一个基于Web的前端,被分成单个的代码块或单元.根据需要,单元可以单独运行,也可以一次全部运行.这使得我们可以运行某个场景,看到输出结果,然后回到代码,根据输出结果对代 ...

  5. 2019-04-18 Python Base 1

    C:\Users\Jeffery1u>python Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64 ...

  6. java IO框架分析

    jave.io框架 2010-11-10 22:18:34|  分类: 默认分类|举报|字号 订阅     可从IO的类层次,IO框架的设计模式来论述. 总体来说,IO可以分为字节流和字符流,不同在于 ...

  7. Disruptor使用

    Disruptor作者,介绍Disruptor能每秒处理600万订单.这是一个可怕的数字. disruptor之所以那么快,是因为内部采用环形队列和无锁设计.使用cas来进行并发控制.通过获取可用下标 ...

  8. SSL延迟

    原文链接 据说,Netscape公司当年设计SSL协议的时候,有人提过,将互联网所有链接都变成HTTPs开头的加密链接. 这个建议没有得到采纳,原因之一是HTTPs链接比不加密的HTTP链接慢很多.( ...

  9. SQL优化(SQL TUNING)之10分钟完毕亿级数据量性能优化(SQL调优)

    前几天.一个用户研发QQ找我,例如以下: 自由的海豚. 16:12:01 岛主,我的一条SQL查不出来结果,能帮我看看不? 兰花岛主 16:12:10 多久不出结果? 自由的海豚 16:12:17 多 ...

  10. Android之后台启动Activity

    在实际开发中.Activity须要启动但界面又不能显示出来,这时就须要后台启动.但又不是finish(),这时就要用到Activity中的moveTaskToBack函数,先看下官网 參数nonRoo ...