VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • seek() 方法

用于移动文件的读取指针到指定位置

seek() 方法语法如下:

fileObject.seek(offset[,whence])

参数
offset --偏移量,也就是代表需要移动偏移的字节数
whence:可选,默认值为 0。表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。


with open("writeline.txt") as file2:
       file2.seek(2)
       print(file2.read())


truncate() 方法

用于截断文件并返回截断的字节长度
指定长度的话,就从文件的开头开始截断指定长度,其余内容删除;不指定长度的话,就从文件开头开始截断到当前位置,其余内容删除
可以用seek()方法,把指针定位到指定位置。


with open("newfile1.txt","r+") as file1:
    file1.truncate(5)

with open("newfile1.txt") as file1:
    print(file1.read())


with open("seek.txt","r+",encoding="gbk") as file1:
    file1.seek(16)
    file1.truncate()
    file1.seek(0)
    print(file1.read())


Tell方法
返回文件指针的当前位置

with open("writeline.txt","r") as file2:
    print(file2.read())
    print(file2.tell())
    file2.close()


next() 方法
ython 3 中的 文件 对象不支持 next() 方法。 Python 3 的内置函数 next() 通过迭代器调用 __next__() 方法返回下一项。 在循环中,
next()方法会在每次循环中调用,该方法返回文件的下一行,如果到达结尾(EOF),则触发 StopIteration

如:
with open("china.txt","r",encoding="gbk") as file1:
   num=len(file1.readlines())
   file1.seek(0,0)
   for index in range(num):
     line = next(file1)
     print ("第 %d 行 内容: %s" % (index, line))






相关教程