zoukankan      html  css  js  c++  java
  • python3_文件操作中file.seek()方法

    1、seek函数 

     file.seek(off, whence=0):从文件中移动off个操作标记(文件指针),正往结束方向移动,负往开始方向移动。

    如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。

    file.seek(0)是重新定位在文件的第0位及开始位置
    file = open("test.txt","rw") #注意这行的变动
    file.seek(3) #定位到第3个 

    2、示例

    from sys import argv

    script,input_file = argv

    def print_all(f):
    print f.read()

    def rewind(f):
    f.seek(0)

    def print_a_line(line_count,f):
    print line_count,f.readline()

    current_file = open(input_file)

    print "First let's print the whole file: "

    print_all(current_file)

    print "Now let's rewind,kind of like a tape."

    rewind(current_file)

    print "Now let's print three lines."

    current_line = 1
    print_a_line(current_line,current_file)

    current_line = current_line + 1
    print_a_line(current_line,current_file)

    current_line = current_line + 1
    print_a_line(current_line,current_file)

    3、结果

    其中test.txt内容如下:

    this is the first line content typing in...
    我是从键盘输入的内容,准备写入到文件中.
    这是第三行。
    这是第四行。
    这是第五行。


    4、示例2

    >>> f=open("aaa.txt","w") #以只写的形式打开一个叫做aaa.txt的文件
    >>> f.write("my name is liuxiang,i am come frome china") #写入内容
    >>> f.close() #关闭文件
    >>> f=open("aaa.txt","r") #以只读打开文件
    >>> f.read() #读取内容
    'my name is liuxiang,i am come frome china'
    >>> f.seek(3,0) #“0”代表从文件开头开始偏移,偏移3个单位
    >>> f.read(5) #从偏移之后的指针所指的位置(即“n”)开始读取5个字符
    'name '
    >>> f.tell() #显示现在指针指在哪个位置(即“i”的位置)
    >>> f.readline() #读取这一行剩下的内容
    'is liuxiang,i am come frome china'

    >>> f.seek(0,2) #“2”代表从末尾算起,“0”代表偏移0个单位
    >>> f.read()
    '' #因为是从末尾算起,内容已结束。所以读取内容为空

  • 相关阅读:
    C++为什么不可以把一个数组直接赋值给另一个数组
    Eigen 矩阵库学习笔记
    HTTP请求报文和HTTP响应报文
    剔除三个(包括三个以上)的子串
    c语言实现:4和7幸运数字的题
    oracle顺序控制语句goto、null和分页过程中输入输出存储、java程序的调用过程
    oracle的控制语句if和循环语句loop while for
    oracle函数、包、变量的定义和使用、重点”结构体和数组”
    oracle pl/sql简介、块、过程
    oracle角色
  • 原文地址:https://www.cnblogs.com/mercywym/p/10010146.html
Copyright © 2011-2022 走看看