python文件处理方式。拷贝和修改方式和简单监控日志

发布于:2023-01-02 ⋅ 阅读:(473) ⋅ 点赞:(0)
拷贝文件,打开一个文本文件,读取内容再新建文本文件写入
# coding='utf-8'
# with open('login1.txt','r',encoding='utf-8')as f,\
#         open('login2.txt','w',encoding='utf-8') as f1:
#     res=f.read()
#     f1.write(res)

拷贝文件,打开一个二进制文件,读取内容再新建文件写入
oldpath=input('请输入原地址')
newpath=input('请输入新地址')
with open(fr'{oldpath}','rb')as f,open(fr'{newpath}','wb') as f1:
    while 1:
        res=f.read(1024)
        f1.write(res)
        if not res:
            break
import time
监控文件
with open('login1.txt','r',encoding='utf-8')as f:
    ​​​​​​​f.seek(0,2)
    while True:
        res=f.readline()
        if not res:
            continue
        else:
            print(res,end='')
            time.sleep(5)
文件修改,硬盘不能修改,只能读到内存后重新写入
一、文件修改操作第一种方式,读取全部内容到内存,使用字符串的替换方式替换后,重写入
with open('login3.txt','r',encoding='utf-8')as f:
    res=f.read()#缺点:文件内容全部读取到内存中,文件大的话对内存负担很大
    res=res.replace('2223','严艺')
with open('login3.txt','w',encoding='utf-8')as f:
    f.write(res)
import os
with open('login3.txt','r',encoding='utf-8')as f:
    res=f.readlines()#读出列表后给字列表赋值修改
    print(res)
    res[1]='严艺严艺严艺\n'
    res=''.join(res)
    print(res)
with open('login3.txt','w',encoding='utf-8')as f:
    f.write(res)
with open('login3.txt','r',encoding='utf-8')as f:
    res=list(f.read())读出字符串后强转成列表后插入或赋值修改
    print(repr(res))
    res.insert(5,'yi')
    res=''.join(res)
with open('login3.txt','w',encoding='utf-8')as f:
     f.write(res)

二、逐行读取内容,一边读取一边写入新文件,最后将源文件删除,将新文件名修改为源文件

import os

with open('login3.txt','r',encoding='utf-8')as f1,\
     open('login4.txt','w',encoding='utf-8')as f2:
    for line in f1:
       result=line.replace('严艺','严芑艺')
       f2.write(result)
os.remove('login3.txt')
os.rename('login4.txt','login3.txt')