python3 plistlib讲解,处理XML文件或者XML bytes

python3中plistlib常用的方法有load,loads,dump,dumps,和json中的load,loads,dump,dumps用法类似。

load和dump处理文件,loads和dumps处理二进制。

安装:

pip install plistlib

1.写入文件:dump

import datetime
import time
from plistlib import dump

pl = dict(
    aString = "Doodah",
    aList = ["A", "B", 12, 32.1, [1, 2, 3]],
    aFloat = 0.1,
    anInt = 728,
    aDict = dict(
        anotherString = "<hello & hi there!>",
        aThirdString = "M\xe4ssig, Ma\xdf",
        aTrueValue = True,
        aFalseValue = False,
    ),
    someData = b"<binary gunk>",
    someMoreData = b"<lots of binary gunk>" * 10,
    aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
)
with open("ttt.txt", 'wb') as fp:
    dump(pl, fp)

2.读取文件:load

with open(fileName, 'rb') as fp:
    pl = load(fp)
print(pl["aKey"])

3.转化bytes类型的xml为dict: loads

import datetime
from plistlib import Data,dumps,loads
data= {'aDate': datetime.datetime(2019, 12, 11, 6, 52, 26), 'aDict': {'aFalseValue': False, 'aThirdString': 'Mässig, Maß', 'aTrueValue': True, 'anotherString': '<hello & hi there!>'}, 'aFloat': 0.1, 'aList': ['A', 'B', 12, 32.1, [1, 2, 3]], 'aString': 'Doodah', 'anInt': 728, 'someData': Data(b'<binary gunk>'), 'someMoreData': Data(b'<lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk>')}
byte_data =dumps(data)
print(byte_data)
dict = loads(byte_data)
print(dict)

4.讲dict转化成xml的bytes:dumps

import datetime
from plistlib import Data,dumps,loads
data= {'aDate': datetime.datetime(2019, 12, 11, 6, 52, 26), 'aDict': {'aFalseValue': False, 'aThirdString': 'Mässig, Maß', 'aTrueValue': True, 'anotherString': '<hello & hi there!>'}, 'aFloat': 0.1, 'aList': ['A', 'B', 12, 32.1, [1, 2, 3]], 'aString': 'Doodah', 'anInt': 728, 'someData': Data(b'<binary gunk>'), 'someMoreData': Data(b'<lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk><lots of binary gunk>')}
byte_data =dumps(data)
print(byte_data)
dict = loads(byte_data)
print(dict)

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值