python基础学习-day12==课后作业练习(文件指针的控制操作)

day12 课后作业

1.通用文件copy工具实现**

src_file=input('源文件路径>>: ').strip()
dst_file=input('源文件路径>>: ').strip()
with open(f'{src_file}',mode='rb') as f1,\
    open(f'{dst_file}',mode='wb') as f2:
    for line in f1:
        f2.write(line)

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

r+:# r+模式打开文件,文件不存在报错。文件指针指向开头

with open('test.txt',mode= 'r+b') as f:
    print(f.read())
    f.seek(0, 0)
    f.write("abc123".encode('utf-8'))
    f.seek(0, 0)
    print(f.read())

w+:#w+模式打开文件,文件不存在创建。文件存在,清空文件。文件指针指向开头

with open('test.txt',mode='w+b') as f:
    f.write("abc123".encode("utf-8"))
    f.seek(4, 0)
    res = f.read().decode('utf-8')
    print(res)

a+:#a+模式打开文件,文件不存在创建。文件指针指向结尾

with open('test.txt\n',mode='a+b') as f:
    f.write("abc123".encode("utf-8"))
    f.seek(-9, 2)
    f.seek(-3, 1)
    res2 = f.read().decode('utf-8')
    print(res2)

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

with open("aaa.txt", mode="a+b") as f:
    line1 = f.tell()
    f.write("abcdef1234".encode("utf-8"))
    line2 = f.tell()
    f.seek(line2-line1, 2)
    res = f.read().decode("utf-8")
    print(res)

猜你喜欢

转载自www.cnblogs.com/dingbei/p/12507198.html