python_day13_文件操作常用模块

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37361758/article/details/84180810

json 模块 .json文件

  • json 定义不同语言之间的交互规则
  • 序列化:内存数据转换成字符
  • 反序列化:把字符转为内存数据
  • json.dumps()序列化
  • json.dump(obj,fp,…) 序列化并写入文件obj为变量名 fp文件名(name.json文件需要提前打开
  • json.loads() 反序列化把字符串转为内存变量
  • json.load(filename) 从文件进行反序列化

pickle 模块 .pkl文件

  • pickle.dumps() pickle序列化为bytes

  • pickle.dump()

  • pickle.loads()

  • pickle.load()

  • load(s)、dump(s) 不可执行多次。

  • json:支持 str, int , tuple, list, dict,

  • pickle: 支持python里所有的数据类型, 但是只能在python里使用

shelve 模块

  • 可dump load 多次
  • import shelve
    f = shelve.open(filename)

  • shelve.open() 有writeback参数, 默认值为False 改为True时,可对文件内容修改

xml 模块

configparser 模块(解析配置文件)

  • config.ini 文件

  • config = configparser.ConfigParser()
    conf.read(“conf.ini”)
    print(dir(conf))
    print(config.sections())
    print(conf.default_section)
    print(conf[“bitbucket.org”]))

  • 注释1

    ; 注释2

    [section1]
    k1 = v1
    k2:v2

    [section2]
    k1 = v1

    import ConfigParser

    config = ConfigParser.ConfigParser()
    config.read(‘i.cfg’)

    #secs = config.sections()
    #print secs
    #options = config.options(‘group2’)
    #print options

    #item_list = config.items(‘group2’)
    #print item_list

    #val = config.get(‘group1’,‘key’)
    #val = config.getint(‘group1’,‘key’)

    #sec = config.remove_section(‘group1’)
    #config.write(open(‘i.cfg’, “w”))

    #sec = config.has_section(‘wupeiqi’)
    #sec = config.add_section(‘wupeiqi’)
    #config.write(open(‘i.cfg’, “w”))

    #config.set(‘group2’,‘k1’,11111)
    #config.write(open(‘i.cfg’, “w”))

    #config.remove_option(‘group2’,‘age’)
    #config.write(open(‘i.cfg’, “w”))

猜你喜欢

转载自blog.csdn.net/weixin_37361758/article/details/84180810