python 2020/8/10

习题4:把一个文件内容中的boy替换成xxx
with open('e:\\aaa.txt','r+',encoding='utf-8')as fp:
    content=fp.read()
    content=content.replace('boy','xxx')
    fp.seek(0,0)
    fp.write(content)

#2
with open('e:\\aaa.txt','r+',encoding='utf-8')as fp:
     content=fp.readlines()
     fp.seek(0,0)
     for line in content:
          fp.write(line.replace('boy','xxx'))


习题5:一个文件拆分成5个文件
file_obj1 = open("e:\\a.txt","r",encoding="utf-8")
file_no = 1  #文件名称的序号名
file_line = 0 #记录文件行数
backup_content = "" #要写的内容
for line in file_obj1: #遍历文件
    file_line += 1  
    backup_content += line   
    if file_line %2 ==0:
        with open("e:\\test"+str(file_no)+".txt","w",encoding="utf-8") as file_obj2:
            file_obj2.write(backup_content)
        file_no +=  1
        backup_content = "" #初始化backup_content

习题6:过滤掉一个文件中空行
with open('e:\\a.txt','r',encoding='utf-8')as fp:
    for line in fp:
        if line.strip()=='':
            continue
        with open('e:\\33.txt','a',encoding='utf-8')as fp:
            fp.write(line)


习题7:处理数据文件

with open('e:\\a.txt','r',encoding='utf-8')as fp:
    content=fp.readlines()
    for line in content:
        with open('e:\\'+line[:14]+'.txt','w',encoding='utf-8')as fp:
            fp.write(line[14:])
#2
with open('e:\\a.txt','r',encoding='utf-8')as fp:
    for line in fp:
        file_name=line[:14]+'.txt'
        file_content=line[14:]
        with open('e:\\'+file_name,'w',encoding='utf-8') as fp:
            fp.write(file_content)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值