zoukankan      html  css  js  c++  java
  • shutil模块 + shelve模块 二合一版

    其他的看我前面的博客

    import shutil

    # 将文件内容拷贝到另一个文件
    with open('old.xml','r') as read_f,open('new.xml', 'w') as write_f:
    shutil.copyfileobj(read_f,write_f)


    # 将文件打包到当前程序所在的目录,可以在打包文件前加上需要打包到的目录,压缩包会打包到该目录。
    shutil.make_archive("data_bak", 'gztar', root_dir='D:SH_fullstack_s2day04')

    import tarfile
    t=tarfile.open('data_bak.tar.gz','r')
    t.extractall('D:SH_fullstack_s2day20dir') # 解压到指定目录
    t.close()

    shutil.copymode(src, dst)
    # 仅拷贝权限。内容、组、用户均不变
    shutil.copymode('f1.log', 'f2.log') # 目标文件必须存在

    shutil.copystat(src, dst)
    # 仅拷贝状态的信息,包括:mode,bits, atime, mtime, flags
    shutil.copystat('f1.log', 'f2.log') # 目标文件必须存在

    # 拷贝文件
    shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在


    shelve序列化模块

    shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型。

    import shelve

    dic1={'pwd':'alex3714','age':18,'sex':'male'}
    dic2={'pwd':'alex3715','age':73,'sex':'male'}

    d=shelve.open('db.txt',writeback=True) # writeback 写回
    print(d) # d就是一个对象 <shelve.DbfilenameShelf object at 0x00000192FD9F0A90>
    d['egon']=dic1 # 相当于序列化
    d['alex']=dic2
    d['egon']['age']=19
    print(d['egon']) # 相当于反序列化 {'pwd': 'alex3714', 'age': 19, 'sex': 'male'}
    d.close()


  • 相关阅读:
    POJ 1797 Heavy Transportation
    洛谷 P3379 【模板】最近公共祖先(LCA)
    洛谷 P1351 联合权值
    51nod 1272 最大距离
    codevs 1664 清凉冷水
    COGS 1176. [郑州101中学] 月考
    HDU
    HDU
    一坨计算几何的板子
    bzoj2618[Cqoi2006]凸多边形
  • 原文地址:https://www.cnblogs.com/Roc-Atlantis/p/9224853.html
Copyright © 2011-2022 走看看