python的文件读写,序列化,复制/删除目录,压缩/解压缩/列出压缩文件目录,计算CRC32和MD5

import json
import os
import shutil
import pickle
import zlib
import binascii
import hashlib
import zipfile
from random import randint
s="你好世界!\nHello World!"
print("文件读写".center(60,"-"))
with open("E://test.txt","w") as fp:
    fp.write(s)
with open("E://test.txt") as fp:
    print(fp.read())#readline()读取一行
    fp.seek(2)
    print("seek()移动游标读取1个字符:",fp.read(1))
t=''.join(map(str,list(randint(1,10) for i in range(10))))
lt=""
print("将随机字符串写入文件1:",t)
with open("E://test2.txt","w",encoding="utf8") as fp:
    fp.write(t)
with open("E://test2.txt","r",encoding="utf8") as fp:
    lt=fp.read()
lt=''.join(map(str,sorted(list(map(int,lt)))))
print("读取字符串排序后写入文件2:",lt)    
with open("E://test2_new.txt","w",encoding="utf8") as fp:
    fp.write(lt)    
print("序列化".center(60,"-"))
x=json.dumps("一龥")
print("json序列化:",x)
print("json反序列化:",json.loads(x))
d1=820
d2=1.23
d3='魑魅魍魉'
d4=(9,5,1)
d5={'a':'又','b':'双','c':'叒','d':'叕'}
d=[d1,d2,d3,d4,d5]
with open("E://pickle.dat","wb") as fp:
    try:
        pickle.dump(len(d),fp)
        for i in d:
            pickle.dump(i,fp)
        print("\npickle序列化成功!")
    except:
        print("\npickle序列化失败!")
print("pickle反序列化:")        
with open("E://pickle.dat","rb") as fp:
    for i in range(pickle.load(fp)):
        print(pickle.load(fp))        
print("文件操作".center(60,'-'))
print("列出该文件目录下扩展名为py的文件名:",list(f for f in os.listdir(os.getcwd()) if os.path.isfile(f) and f.endswith('.py')))
print("将该文件目录下txt的文件扩展名更改为dat:")
f_list=list(f for f in os.listdir(os.getcwd()) if f.endswith('.txt'))
for f in f_list:
    new_name=f[:-3]+"dat"
    os.rename(f,new_name)
    print(f+"更改为"+new_name)
print("复制文件",shutil.copyfile("E://被复制.txt","E://复制.txt"))
print("压缩文件:",shutil.make_archive("E://PNG","zip","E://Study","PNG"))
print("解压文件:",shutil.unpack_archive("E://PNG.zip","E:/"))
print("删除解压的文件夹:",shutil.rmtree("E://PNG"))
print("用zlib计算CRC32值(循环冗余校验):",zlib.crc32('1234'.encode()))
print("用binascii计算CRC32值(循环冗余校验):",binascii.crc32("1234".encode()))
print("计算MD5的值(信息摘要算法):",hashlib.md5('1234'.encode()).hexdigest())
print("查看zip压缩文件的文件列表:")
with zipfile.ZipFile('E://PNG.zip') as fp:
    for f in fp.namelist():
        print(f)

在这里插入图片描述
序列化的文件用记事本查看为乱码
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章