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_s2\day04')

import tarfile
t=tarfile.open('data_bak.tar.gz','r')
t.extractall('D:\SH_fullstack_s2\day20\dir') # 解压到指定目录
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()


猜你喜欢

转载自www.cnblogs.com/Roc-Atlantis/p/9224853.html