文件写入
scores = [88 , 99 , 90 , 56]
def write_scores():
with open("data_list.txt","w",encoding="utf8") as f:
f.write(str(scores))
print("文件写入完成")
if __name__ == '__main__':
write_scores()
结果是:
建立了一个新的data_list.txt,里面写入了scores的[88,99,89,56]
并线执行串口显示:文件写入完成
with open("data.txt","w",encoding="utf8") as f:
f.write("财管会计\n")
f.write("codeclassroom.com")
结果是:建立了一个新的data_list.txt,里面写入了
财管会计
codeclassroom.com
scores = [88, 99, 90, 56]
def write_scores():
with open("data_list.txt","w",encoding="utf8") as f:
f.write(str(scores))
print("文件写入完成")
def read_scores():
with open("data_list.txt","r",encoding="utf8") as f:
lst = eval(f.read())
lst[0] = 99
print(lst)
if __name__ == '__main__':
read_scores()
结果是:
[99, 99, 90, 56]
但是data_list.txt里面还是原来的[88, 99, 90, 56]
pickle
shelve
import shelve
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return self.name
def write_shelve():
s = Student("tom",20)
db = shelve.open("shelve_student_db")
db["s"] = s
db.close()
if __name__ == '__main__':
write_shelve()
import shelve
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return self.name
def write_shelve():
s = Student("tom",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__':
read_shelve()
结果是:
tom
tom
20