zoukankan      html  css  js  c++  java
  • day7 文件管理

    1.bytes 类型转成utf-8可以存硬盘,可以基于网络传输

    ,转移

    2、b模式

    文件的打开模式b模式
    强调:
    1、与t模式类似不能单独使用,必须是rb,wb,ab

    rb模式

    with open('l.txt',mode='r',) as f:

    data=f.read()

    print(data.decode('utf-8'))

    print(type(data))

    wb模式

    with open ('b.txt',code='wb') as f:

    msg='你好'

    f.write(msg.encode('gbk'))

    with oper('1.jpg',mode='rb') as f:

      data=f.read()

      print(type(data))

      print(data.decode('utf-8'))

    2、b模式下读写都是以bytes单位的
    3、b模式下一定不能指定encoding参数

    seek(n)n=1,2,3,偏移量的单位是字节

    with open('user.txt','r+',encoding='utf-8')

      f.seek(5)

    print(f.tell())

    print(f.reak())

    ab 模式

    with open('b.txt',mode='ab') as f:

      f.write('你好'.encode('utf-8'))

    修改文件方式 一:

    1、先把文件内容全部读入内存

    2、然后在内存中完成修改

    3、再把修改后的文件覆盖写入原文件

    缺点:点内存

    with open('user.txt',mode='r',encoding='utf-8') as f:

      data=f.read()

      data=data.replace('aa','bb' )

    with open('user.txt',mode='w',encoding='utf-8') as f

      f.write(data)

    修改文件方式二:

    1、以读找开原文件,以的方式打开一个新文件并把原文件删除,占空间

    import os

    with open('user.txt',mode='r',encoding='utf-8') as old_f,

    open('user1.txt',mode='r',encoding='utf-8') as new_f

    for i in old_f

      if 'aa' in i:

      i=i.replace('aa','bb')

    new_f.write(i)

    os.remove('user.txt')

    os.remove('user1.txt','user')

    两种方式各有利敝

  • 相关阅读:
    javascript 面向对象 new 关键字 原型链 构造函数
    前端性能优化之gzip
    电子商务秒杀所带来的问题
    git 远程版本库,github提供服务原理,git自动更新发送邮件
    单点登陆的三种实现方式(详解)
    使用php实现单点登录
    支付宝异步回调
    http状态码大全
    php 单向散列加密
    curl模拟post请求
  • 原文地址:https://www.cnblogs.com/lg04551/p/8630159.html
Copyright © 2011-2022 走看看