其他分享
首页 > 其他分享> > day12

day12

作者:互联网

1、通用文件copy工具实现

src_file = input('请输入源文件地址:').strip()
dsc_file = input('请输入目标地址:').strip()
with open(r'{}'.format(src_file), mode='rb')as f1,\
        open(r'{}'.format(dsc_file), mode='wb')as f2:
    for line in f1:
        f2.write(line)

2、基于seek控制指针移动,测试r+、w+、a+模式下的读写内容

r+模式 的模式 0:

with open('c.txt', mode='r+t', encoding='utf-8')as f:
    l = ['中国\n','hello\n','haha\n']
    f.seek(3, 0)
    print('1',f.tell()) #3
    print(f.readlines()) #['国\n', 'hello\n', 'haha\n', '\n']
    print('2',f.tell()) #19
    f.writelines(l)
    print('3',f.tell()) #37
    res = f.readlines()
    print('4',f.tell())#37
    print(res) #[]

w+模式的模式 0:

with open('c.txt', mode='w+t', encoding='utf-8')as f:
    l = ['11\n','22\n','33\n']
    f.writelines(l)
    f.seek(2, 0)
    res = f.readlines()
    print(res) #['\n', '22\n', '33\n']

a +模式的模式 0:

#文本:haha

with open('c.txt', mode='a+t', encoding='utf-8')as f:
    l = ['中国\n','hello\n','haha\n']
    print('1',f.tell()) #5
    print(f.readlines()) #[]
    f.writelines(l)
    print('2',f.tell()) #23
    res = f.readlines()
    print('3',f.tell())#23
    print(res) #[]
    f.seek(2, 0) #
    print('4',f.tell()) # 2
    print(f.readlines()) #['ha\n', '中国\n', 'hello\n', 'haha\n']

3、tail -f access.log程序实现

import time

with open('access.log', mode='rb')as f:
    f.seek(0, 2)
    print(f.tell())
    while True:
        res = f.readline()
        print(res)
        if res:
            print(res.decode('utf-8'), end='')
        else:
            time.sleep(2)
            print('xxxx')

标签:res,readlines,mode,day12,print,open,tell
来源: https://www.cnblogs.com/xy-han/p/12506525.html