python的os模块

Name

os ——OS routines for Mac, NT, or Posix depending on what system we’re on.
.
Programs that import and use ‘os’ stand a better chance of being portable between different platforms. Of course, they must then only use functions that are defined by all platforms (e.g., unlink and opendir), and leave all pathname manipulation to os.path (e.g., split and join).

Functions

// 将当前工作目录更改为指定路径

os.chdir(path)

// 返回文件描述符的副本

os.dup(fd) —>fd2

// 返回表示当前工作目录的字符串

os.getcwd() —>path

// 返回表示当前工作目录的unicode字符串

os.listdir() ->path

// 创建一个目录

os.mkdir(path[,mode=0777])

// 打开文件(对于低级别IO)

os.open(filename,flag[,mode=0777]) ->fd

// 读取一个文件描述符

os.read(fd,buffersize) ->string

// 重命名一个文件或者目录

os.rename(old,new)

// 删除目录

os.rmdir(path)

// 删除文件

os.remove(path)

扫描二维码关注公众号,回复: 876208 查看本文章
// 删除文件(与remove(path)相同

os.unlink(path)

// 目录树生成器, 对于目录树中的每个目录, 在顶部开始翻寻 (包括顶部本身, 但排除 ‘.’ 和 ‘..’ ), 生成一个3元组(‘目录x’, list(目录x下的目录), 目录x下的文件)

os.walk(top,topdown=True,onerror=None,followlinks=False)

// os提供的path模块

// 判断name是一个目录,而不是一个文件

os.path.isdir(name) —>True/False

// 判断name是一个文件,而不是一个目录

os.path.isfile(name) —>True/False

// 判断name文件或者目录是否存在

os.path.exists(name) —>True/False

// 获得name文件的大小,如果是目录返回0

os.path.getsize(name)

// 获得绝对路径

os.path.abspath(name)

// 规范path字符串形式

os.path.normpath(path)

// 分割目录与文件名,默认最后一个是文件名

os.path.split(path)

// 分离文件名与扩展名

os.path.splitext(name)

// 连接目录与文件名或目录

os.path.join(path,name)

// 返回文件名,默认最后一个是文件名

os.path.basename(path)

// 返回文件路径,默认最后一个是文件名

os.path.dirname(path)

Example

import os
for root, dirs, files in os.walk('C:\Tencent'):
        for name in files:
            print(os.path.join(root,name))
        for name in dirs:
            print(os.path.join(root,name))

Output :
C:\Tencent\QQ
C:\Tencent\QQ\QQProtect
C:\Tencent\QQ\QQProtect\SFU

猜你喜欢

转载自blog.csdn.net/sinat_24648637/article/details/80296378