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)