Python文件指针

实验文件data.txt如下:

This file is data.txt
hello world!
My name is mark.

实验一、文件指针初始化

f = open('data.txt','r+')
print f.tell()
f.write('nice to meet you')
f.flush()
print f.tell()
print f.read()
f.close()

相应输出:
//print f.tell()
0
//print f.tell()
16
//print f.read()
a.txt
hello world!
My name is mark.

以’r+‘模式打开文件,文件指针所指位置为0
f.write(‘nice to meet you’)会覆盖原文件内容,文件指针随着移动
print f.read()只会输出剩余内容

f = open(r'test2.txt','a+')
print f.tell()
f.write('nice to meet you')
f.flush()
print f.tell()
print f.read()
f.close()

相应输出:
//print f.tell()
52
//print f.tell()
68
//print f.read()

以’a+’模式打开,文件指针所指位置为文件尾,此例为52
f.write(‘nice to meet you’)会在原文件内容尾添加,文件指针随着移动至68
因为随着write()函数,文件指针已经移到文件末尾,所以print f.read()没有输出

实验二、文件指针的移动

f = open(r'test2.txt','r+')
print f.tell()
f.seek(0,0)
print f.tell()
f.write('nice to meet you')
f.flush()
print f.tell()
f.seek(0,0)
print f.read()
f.close()

相应输出:
//print f.tell()
0
//print f.tell()
0
//print f.tell()
16
//print f.read()
nice to meet youa.txt
hello world!
My name is mark.

以’r+‘模式打开文件,文件指针所指位置为0
f.seek(0,0),文件指针指向位置0
f.write(‘nice to meet you’)从位置0开始覆盖原文件内容,文件指针随着移动
‘nice to meet you’替换了原文件

f = open(r'test2.txt','a+')
print f.tell()
f.seek(0,0)
print f.tell()
f.write('nice to meet you')
f.flush()
print f.tell()
f.seek(0,0)
print f.read()
f.close()
相应输出:
//print f.tell()
52
//print f.tell()
0
//print f.tell()
68
//print f.read()
This file is data.txt
hello world!
My name is mark.
nice to meet you

以’a+’模式打开,文件指针所指位置为文件尾,此例为52
f.seek(0,0),文件指针指向位置0
f.write(‘nice to meet you’)从位置52开始添加,文件指针随着移动至68
新添加了’nice to meet you‘

Note:以’a+’模式打开文件,虽然以f.seek(0,0)将文件指针指向文件开头,但使用f.write()函数时,会重置文件指针,默认从文件末尾添加

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值