标签:shel val tom load 反序 core main eval 类型
scores = [88, 99, 77, 55]
def write_scores():
with open('datafile.txt', 'w', encoding = 'utf8') as f: #文件仅含一个列表
f.write(str(scores))
print('文件写入完成...')
def read_scores():
with open('datafile.txt', 'r', encoding='utf8') as f:
lst = eval(f.read()) #转换数据类型
lst[0] = 99
print(lst)
if __name__ == '__main__':
#write_scores() #先运行写入函数
read_scores()
[99, 99, 77, 55]
import pickle
person = {'name':'Tom', 'age':20}
s = pickle.dumps(person) #把任意类型对象序列化成字符串
s
p = pickle.loads(s) #反向转换
p
b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x03\x00\x00\x00Tomq\x02X\x03\x00\x00\x00ageq\x03K\x14u.'
{'name': 'Tom', 'age': 20}
pickle.dump(person, open('pickle_db', 'wb'))
p = pickle.load(open('pickle_db', 'rb'))
p
type(p)
{'name': 'Tom', 'age': 20}
dict
import shelve
scores = [99, 88, 77]
student = {'name':'Mike', 'age':20}
db = shelve.open('shelve_student') #创建数据库文件
db['s'] = student
db['scores'] = scores
len(db) #有两个键值
temp_student = db['s']
temp_student
type(temp_student)
2
{'name': 'Mike', 'age': 20}
dict
del db['scores']
len(db)
1
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name
def write_shelve():
s = Student('Yom', 20)
db = shelve.open('shelve_student_db')
db['s'] = s
db.close()
def read_shelve():
db = shelve.open('shelve_student_db')
st = db['s']
print(st)
print(st.name)
print(st.age)
db.close()
if __name__ == '__main__':
#write_shelve() #先写入再读取
read_shelve()
Yom
Yom
20
标签:shel val tom load 反序 core main eval 类型
原文地址:https://www.cnblogs.com/linyk/p/11483401.html