File basic Operation 2:tell, Seek
One of the traversal methods: iterators
ReadLines method Disadvantage: ReadLines is to put the file into a list form into the memory, if the file is large, all of a sudden into the list, the system burden is too heavy, so readlines not often used.
# -*-coding:utf-8 -*-__author__ = ‘xiaojiaxin‘__file_name__ = ‘file3‘#Readlines方法缺点:readlines是把文件变成列表形式存入内存里面,如果文件很大,一下子全部变成列表,系统负担太重,所以readlines不常使用。f=open("小重山",mode="r",encoding="utf-8")#迭代器:用的时候拿一行取一行,不用就不取#f已经写入磁盘了,这里for循环并没有对磁盘进行任何操作,而是for内部把f对象做成了迭代器counter=0for i in f: #这种遍历方法最优 counter+=1 if counter==6: i="".join([i.strip(),"i like it!"]) print(i.strip())f.close()# 昨夜寒蛩不住鸣。# 惊回千里梦,已三更。# 起来独自绕阶行。# 人悄悄,帘外月胧明。# 白首为功名,旧山松竹老,阻归程。# 欲将心事付瑶琴。i like it!# 知音少,弦断有谁听。
Tell方法
#tell:检测文件指针的位置,很重要f1=open("小重山",mode="r",encoding="utf-8")print(f1.tell())print(f1.read(3))print(f1.tell()) #显示指针的移动位置f1.close()#一个中文字符占3个字节,一个英文字符占1个字节# 0# 昨夜寒# 9
Seek method
#任意调整光标位置 seek 很重要!!!!!应用:重传数据f2=open("小重山",mode="r",encoding="utf-8")print(f2.read(3))print(f2.tell()) #显示指针的移动位置print(f2.seek(0))print(f2.tell())f2.close()# 昨夜寒# 9# 0# 0
4.2Python file Basic Operation 2:tell, Seek