py08-文件处理-02

1、文件的其他操作

with open('a.txt','r',encoding='utf-8') as f:
    print(f.read())
    print('########')
    print(f.read())

#读取所有内容,第二次读取的时候为空

 2、文件内光标移到

  read(3):

  1、文件打开方式为文本模式时,代表读取3个字符

with open('a.txt','r',encoding='utf-8') as f:
    print(f.read(3))

   2、文件打开方式为b模式时,代表读取3个字符

with open('a.txt','rb') as f:
    print(f.read(3).decode('utf-8'))

3、其余的文件光标移动都是以字节为单位

   如:seek、tell、truncate

    注意:

  1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的

    0是开头

    1是当前位置

    2是结尾

with open('a.txt','r',encoding='utf-8') as f:
    print(f.read())
    f.seek(0)        #将光标移动开头,
    print('####')
    print(f.read())     #光标移动到开头,然后读取
with open('a.txt','r',encoding='utf-8') as f:
    print(f.read())
    f.seek(3)        #起始点开头移动3个字符 等价于 f.seek(3,0)
print(f.read())

with open('a.txt','rb') as f:
    print(f.read(3))          #读取3个字符
    f.seek(2,1)             #在当前3个字符的光标移动2个字符  
    print(f.tell())  
    print(f.read().decode('utf-8'))
with open('a.txt','rb') as f:
    f.seek(0,2)
    print(f.tell())

(2是末尾,打开文件就跳转至末尾,很重要,很重要)

 4、tail程序实例

import time
import  sys
#python3 tail.py -f access.log
if len(sys.argv) < 2:
    print('Usage: python3 tail.py -f access.log ')
    sys.exit()
with open(r'%s'%sys.argv[2],'rb') as f:
    f.seek(0,2)
    while True:
        line=f.readline()
        if line:
            print(line.decode('utf-8'),end='')
        else:
            time.sleep(0.2)

 

posted @ 2017-08-07 14:10  sysgit  阅读(123)  评论(0编辑  收藏  举报