python文件的基本操作之控制文件指针

1.文件基本操作

#r+t:可读、可写

#w+t:可写、可读

#a+t:可追加写、可读

#####r+b  w+b  a+b 一样的#####

2.文件光标的移动

     f.seek(offset,whence)
    #offset代表文件的指针的偏移量,单位是字节bytes
    #whence代表参考物,有三个取值
    #0:参照文件的开沟
    #1:参照当前文件指针所在位置
    #2: 参照文件末尾

    #ps:快速移动到文件末尾f.seek(0,2)

    f.tell #每次统计都是从文件头到当前指针所在位置

####只要在t 模式在是read(n)n代表字符个数,除此之外的文件指针都是以bytes为单位

    # f=open('c.txt',mode='rt',encoding='utf-')
    # print(f.read(3))
    # f.close()

    # f=open('c.txt',mode='rb',)
    # print(f.read(3).decode('utf-8'))
    # f.close()

    f.truncate()                   #截断,参照物永远都是文件开头

       f=open('b.txt',mode='at',)
       f.truncate(9) # 参照物永远是文件开头 ,之后的全部删除
        f.close()                                     

原文地址:https://www.cnblogs.com/Marcki/p/10111969.html