持久化文件读写:
1
2
3
4
5
6
|
f = open ( 'info.txt' , 'a+' ) f.seek( 0 ) str1 = f.read() if len (str1) = = 0 : f1 = open ( 'info.txt' , 'w+' ) str1 = f.read() |
# 如果数据没有就写入数据到文件
1
2
3
4
5
6
7
8
9
|
time_list = [ "早上" , "中午" , "晚上" ] character_list = [ "小赵" , "小钱" , "小孙" , "小李" ] place_list = [ "在屋里" , "在外面" , "在学校" , "在公司" ] event_list = [ "吃饭" , "遛狗" , "看书" , "工作" ] dic1 = { 'time_list' :time_list, 'character_list' :character_list, 'place_list' :place_list, 'event_list' :event_list} str1 = str (dic1) f1.write(str1) f1.close() print ( "文件保存成功" ) |
# 如果数据有,就字符串转换为字典
1
2
3
4
5
6
7
8
9
10
11
|
else : dic1 = eval (str1) print ( type (dic1)) print (dic1) f = open ( 'info.txt' , 'a+' ) f.seek( 0 ) str1 = f.read() if len (str1) = = 0 : f1 = open ( 'info.txt' , 'w+' ) str1 = f.read() |
# 如果数据没有就写入数据到文件
1
2
3
4
5
6
7
8
9
|
time_list = [ "早上" , "中午" , "晚上" ] character_list = [ "小赵" , "小钱" , "小孙" , "小李" ] place_list = [ "在屋里" , "在外面" , "在学校" , "在公司" ] event_list = [ "吃饭" , "遛狗" , "看书" , "工作" ] dic1 = { 'time_list' :time_list, 'character_list' :character_list, 'place_list' :place_list, 'event_list' :event_list} str1 = str (dic1) f1.write(str1) f1.close() print ( "文件保存成功" ) |
# 如果数据有,就字符串转换为字典
1
2
3
4
|
else : dic1 = eval (str1) print ( type (dic1)) print (dic1) |
以上所述是小编给大家介绍的python持久化文件读写详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://blog.csdn.net/weixin_44607176/article/details/88667106