详解python持久化文件读写

yipeiwu_com5年前Python基础

持久化文件读写:

f=open('info.txt','a+')
f.seek(0)
str1=f.read()
if len(str1)==0:
  f1 = open('info.txt', 'w+')
  str1 = f.read()

# 如果数据没有就写入数据到文件

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("文件保存成功")

# 如果数据有,就字符串转换为字典

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()

# 如果数据没有就写入数据到文件

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("文件保存成功")

# 如果数据有,就字符串转换为字典

else:
    dic1=eval(str1)
    print(type(dic1))
    print(dic1)

以上所述是小编给大家介绍的python持久化文件读写详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Python下线程之间的共享和释放示例

最近被多线程给坑了下,没意识到类变量在多线程下是共享的,还有一个就是没意识到 内存释放问题,导致越累越大 1.python 类变量 在多线程情况 下的 是共享的 2.python 类变量...

Mac在python3环境下安装virtualwrapper遇到的问题及解决方法

前言 我在使用mac安装virtualwrapper的时候遇到了问题,搞了好长时间,才弄好,在这里总结一下分享出来,供遇到相同的问题的朋友使用,少走些弯路。 问题说明: Mac默认系...

pytorch实现用CNN和LSTM对文本进行分类方式

model.py: #!/usr/bin/python # -*- coding: utf-8 -*- import torch from torch import nn imp...

python3+PyQt5 数据库编程--增删改实例

python3+PyQt5 数据库编程--增删改实例

本文通过python3+pyqt5改写实现了python Qt gui 编程变成15章的excise例子。 #!/usr/bin/env python3 import os impo...

python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)

python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)

python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换) Python3 JSON 数据解析...