python入门作业——文件管理b模式的应用

1、通用文件copy工具实现

old_file=input('要复制的文件路径>>: ').strip()
new_file=input('复制到文件路径>>: ').strip()
with open(r'{}'.format(old_file),mode='rb') as f1,\
    open(r'{}'.format(new_file),mode='wb') as f2:
#     res=f1.read() # 该方法可能会导致内存占用过大
#     f2.write(res)
    for line in f1:
        f2.write(line)

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

  r+

with open('aaa.txt',mode='wt',encoding='utf-8') as f:   # 创建一个文文件
    f.write('123abc你好')
with open('aaa.txt',mode='r+b') as f:
    f.seek(3,0)  # 0从头开始 指针往前移动3格
    print(f.tell())  # 指针在3位置
    # print(f.read())  # abc你好
    f.seek(3,1)  # 从3开始往前移动3格
    print(f.tell())  # 指针在6位置
    # print(f.read().decode('utf-8'))  # 你好
    f.seek(-3,2)  # 指针从末位开始往前三个位置
    print(f.tell())  # 指针在9位置  汉字一个3字节
    print(f.read().decode('utf-8'))  #

  w+

with open('aaa.txt',mode='w+b') as f:
    f.write('123abc你好'.encode('utf-8'))  # 输入完内容指针在最后
    f.seek(3,0) # 0从头开始 指针往前移动三格
    print(f.tell())  # 指针在3位置
    # print(f.read())  # b'abc\xe4\xbd\xa0\xe5\xa5\xbd'
    # print(f.read().decode('utf-8')) # abc你好  上下两个print只能取一个  因为一个读完指针就到了最后 下面的print就读不出东西了
    f.seek(3,1)  # 从3开始往前移动3格
    print(f.tell())  # 指针在6位置
    # print(f.read().decode('utf-8'))  # 你好
    f.seek(-3,2)   # 指针从末位开始往前三个位置
    print(f.tell())  # 指针在9位置  汉字一个3字节
    print(f.read().decode('utf-8'))  #

  a+

with open('aaa.txt',mode='a+b') as f:
    f.seek(3,0) # 0从头开始 指针往前移动三格
    print(f.tell())  # 指针在3位置
    # print(f.read())  # b'abc\xe4\xbd\xa0\xe5\xa5\xbd'
    # print(f.read().decode('utf-8')) # abc你好  上下两个print只能取一个  因为一个读完指针就到了最后 下面的print就读不出东西了
    f.seek(3,1)  # 从3开始往前移动3格
    print(f.tell())  # 指针在6位置
    # print(f.read().decode('utf-8'))  # 你好
    f.seek(-3,2)   # 指针从末位开始往前三个位置
    print(f.tell())  # 指针在9位置  汉字一个3字节
    print(f.read().decode('utf-8'))  #

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

import time
with open('access.log',mode='wb') as f:
    f.write('123abc你好') # 创建一个文件并输入点内容
with open('access.log',mode='rb') as f:
    f.seek(0,2)
    while True:
        line=f.readline()
        if len(line) == 0: #如果没有内容那就延迟五秒后再运行while循环
            # 没有内容
            time.sleep(5) #延迟五秒
        else:
            print(line.decode('utf-8'),end='') #输出指针后面的内容

 

posted @ 2020-03-16 20:39    阅读(193)  评论(0编辑  收藏  举报