python学习-37 其他的文件处理方法

f = open('test.txt','r+',encoding='utf-8')

f.flush()        # 刷新

f.readline()
print(f.tell())     # 说明光标位置在哪里 (
 也算两个字节)
print('-------------------------------')

f.seek(3)                      # 在文件test.txt里第一行abc123,  3的位置
print(f.tell())
print(f.read())

f.truncate(10)                # 截取

运行结果:

7
-------------------------------
3
13
123

Process finished with exit code 0

seek 方法的补充

1.光标的移动

f = open('test.txt','rb')              # 以2进制的方式
print('目前光标的位置:',f.tell())
print('--------------------')

f.seek(10)
print(f.tell())
print('-------------')

f.seek(3)                               # 默认从文件开始计算光标位置
print(f.tell())
print(f.read())
print('-------------')

f.seek(10,1)                        #  相对路径,从上一步的光标位置开始计算10字节
print(f.tell())
print('--------------')

f.seek(-10,2)                # 从文件末尾位置开始计算10字节
print(f.tell())              # 光标在从前往后数的第40字节的位置
print(f.read())               # 读取现在光标的位置
print('-----------')

运行结果:

目前光标的位置: 0
--------------------
10
-------------
3
b'13
123
xe4xbdxa0xe5xa5xbd
hello,word
qwertyuiop46579813'
-------------
60
--------------
40
b'op46579813'
-----------

Process finished with exit code 0

 2.想要查看文件的最后一行

f = open('test.txt','rb')
for i in f:
    offs = -10
    while True:
        f.seek(offs,2)
        data = f.readlines()
        if len(data) >1:
            print('文件的最后一行是%s'%(data[-1].decode('utf-8')))
            break
        offs *= 2

运行结果:

文件的最后一行是2019/7/11/20:56     qwe456

Process finished with exit code 0
原文地址:https://www.cnblogs.com/liujinjing521/p/11172554.html