day12作业

1、通用文件copy工具实现

ald_file = input('原文件路劲:').strip()
new_file = input('新文件路径:').strip()
with open(r'{}'.format(ald_file), 'rb') as f, \
        open(r'{}'.format(new_file), 'wb') as f1:
    data = f.read()
    f1.write(data)

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

#  r+模式下打开文件读取完数据 光标会自动移动到文件末尾
with open('user_db', 'r+t', encoding='utf-8') as f:
    f.seek(6, 0)  # 控制指针移动到第六个字符后面
    print(f.tell())  # 打印指针移动后的当前所在的位置(6)
    f.write('hello')  # 在第六个7~12字符写入hello
    f.seek(0, 0)  # 指针移动到文件开始位置
    print(f.read())  # 重新打开文件查看123456hello
    # 注意事项文件重新写入内容后会覆盖掉原先位置的内容

#  w+模式下会清空文件内容
with open('user_db', 'w+t', encoding='utf-8') as f:
    f.seek(5, 0)  # 控制指针移动到五个字符后面的位置
    print(f.tell())  # 打印指针当前所在的位置(5)
    f.write('word')  # 在5的位置后面写入word 6~10位置
    f.seek(0, 0)  # 指针回到文件的开头位置
    print(f.read())  # word

# a+模式下 文件内容不会清空 光标会在末尾
with open('user_db', 'a+t', encoding='utf-8') as f:
    print(f.tell())  # 打印光标所在位置(9)
    f.seek(5, 0)  # 光标位置移动到第5个字符后面
    f.write('发发发')  # 在追加模式下光标会跑到文件末尾写入数据 123456789发发发
    f.seek(0, 0)  # 光标回到文件开头
    print(f.read())  # 读取所有内容  123456789发发达

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

# 就是写程序实现读取的数据都是文件追加的数据内容
while 1:
    print('输入任意文字可添加至日志,输入readlog可读取日志信息')
    msg = input('输入指令:').strip()
    if msg == 'readlog':
        with open(r'access.log', 'a+b') as f:
            f.write(bytes('{}\n'.format(msg), encoding='utf-8'))
            f.seek(0, 0)
            log = f.read().decode('utf-8')
            print(log)
        continue
    else:
        with open(r'access.log', 'ab') as f:
            f.write(bytes('{}\n'.format(msg), encoding='utf-8'))
posted @ 2020-03-17 17:50  nick_xm  阅读(110)  评论(0编辑  收藏  举报