Python文件操作,,文件操作模式r 只读


文件操作模式

r 只读

w 只写

a 追加写

r+ 读写

w+ 读写,如果文件已存在则将其删除,不存在则创建新文件

a+ 读写,如果文件已存在则在文件末尾追加,不存在则创建新文件


常用文件操作函数

read() 将文件内容作为一个大的字符串全部读出来

readline() 读取文件中的一行内容

readlines() 将文件内容作为一个大的列表全部读出来,每个成员是文件中的某一行

write() 将字符串写入文件

writelines(list) 将列表写入文件

close() 文件关闭

tell() 当前游标的位置

seek(offset[,where])

把文件指针移动到相对于where的offset位置,where为0表示文件开始处,这是默认值;1表示当前位置;2表示文件结尾

flush() 刷新输出缓存,把缓冲区的内容写入硬盘

truncate([size]) 截取文件,使文件大小为size


代码演示

同一文件夹下有test.txt文件和file.py文件

test.txt文件内容如下:

aaaaa

bbbbb

ccccc

示例一:

fp=open(‘test.txt‘,‘r‘)printfp.nameprintfp.modeprintfp.closedfp.close()printfp.closed

>>>

test.txt

r

False

True

>>>

实例二:

fp=open(‘test.txt‘,‘r‘)printfp.tell()printfp.readline()printfp.tell()fp.seek(0)printfp.readline()printfp.readlines()

>>>

0

aaaaa


7

aaaaa


[‘bbbbb\n‘, ‘ccccc\n‘]

>>>

示例三:

fp=open(‘test1.txt‘,‘w‘)fp.write(‘111\n‘)fp.write(‘222\n‘)fp.writelines([‘111111\n‘,‘222222\n‘])fp.close()

执行之后test1.txt中的内容为:

111

222

111111

222222

示例四:

fp=open(‘test1.txt‘,‘a‘)fp.truncate(2)fp.close()

执行之后test1.txt中的内容为:

11

示例五:

fp=open(‘test.txt‘,‘r+‘)printfp.tell()printfp.readlines()printfp.tell()fp.write(‘ddddd\n‘)fp.flush()fp.seek(0)printfp.readlines()fp.close()

>>>

0

[‘aaaaa\n‘, ‘bbbbb\n‘, ‘ccccc‘]

19

[‘aaaaa\n‘, ‘bbbbb\n‘, ‘cccccddddd\n‘]

>>>


本文出自 “今日的努力,明日的成功!” 博客,请务必保留此出处http://zhzhgo.blog.51cto.com/10497096/1676562

Python文件操作

评论关闭