Python中的io模块基础总结【转】

IO,在计算机中值得input(输入)/output(输出),凡是用到数据交换的地方都会用到IO。

Stream(流) 是一种重要的概念,分为Input Stream(输入流)和Output Stream(输出流)。

打开文件:

open(name[,mode[,buffering]])

name:文件路径,强制参数

model:模式,可选参数

1
2
3
4
5
'r' #读模式
'w' #写模式
'a' #追加模式
'b' #而进制模式,追加到其他模式中
'+' #读/写模式,追加到其他模式中

buffering:缓冲区,可选参数

1
2
3
4
缓冲区参数为0,IO无缓冲,直接写到硬盘上
缓冲区参数为1,IO有缓冲,数据先写到内容中,只有使用flush或者close 才会将数据更新到硬盘上
缓冲区参数为大于1,代表缓冲区的大小,单位为字节
缓冲区参数为小于0,代表使用默认缓冲区大小

默认模式读取模式,默认缓冲区为无

例:

1
2
file = open("ioText.txt",'r')
print file.read()
1
2
3
4
5
6
输出:
Py io test!
 
当模式为r时,如果文件不存在会报出异常
IOError: [Errno 2] No such file or directory: 'txt.txt'
当模式为w时,如果文件不存在会自动创建。

文件操作有可能会出现异常,所以为了程序的健壮性,需要使用try ….finally 来实现,来确保总会调用close方法,

如果没有调用close方法,文件对象会占用操作系统对象,影响系统的io操作。

1
2
3
4
5
6
try:
    file = open("ioText.txt",'r')
    print file.read()
finally:
    if file:
        file.close()

Python 提供了一种简单的写法

1
2
with open("ioText.txt",'r') as file:
    print file.read()

文件读取:

read() #一次将文件内容读到内存

read(size) #一次最多读size个字节

readline() #每次读取一行

readlines() #读取所有内容并按行返回内容

文件写入:

write() #现将数据写入内存中,系统空闲时写入,调用close()完整写入文件

flush() #不断将数据立即写入文件中

常用的文件和目录操作方法:

对文件和目录经常用到OS模块和shutil模块。

os.getcwd() 获取当前脚本的工作路径

os.listdir() 返回指定目录下的所有文件和目录名

os.remove(filepath) 删除一个文件

os.removedirs(path) 删除多个目录

os.path.isfile(filepath) 检验给出的路径是否是一个文件

os.path.isdir(filepath) 检验给出的路径是否是一个目录

os.path.isabs() 判断是否是一个目录

os.path.exists(path) 检测是否有该路径

os.path.split(path) 分离path的目录名和文件名

os.path.splitext() 分离扩展名

os.path.dirname(path) 获取路径名

os.path.basename(path) 获取文件名

os.getenv() 读取环境变量

os.putenv() 设置环境变量

os.linesep 给出当前平台使用的行终止符,win: linux: mac:

os.name 当前使用的平台 win:nt linux/unix:posix

os.rename(old,new) 重命名文件或目录

os.makedirs(path) 创建多级目录

os.makedir(path) 创建单级目录

os.stat(file) 获取文件属性

os.chmod(file) 修改文件权限与时间戳

os.path.getsize(filename) 获取文件大小

os.rmdir(dir) 删除空目录

os.rmtree(dir) 删除目录

shutil.copytree(olddir,newdir) 复制文件夹

shutil.copyfile(oldfile,newfile) 复制文件

shutil.move(oldpos,newpos) 移动文件

原文地址:https://www.cnblogs.com/gabrielle/p/9697834.html