详解python持久化文件读写

yipeiwu_com6年前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实现nao机器人手臂动作控制

本文实例为大家分享了python实现nao机器人手臂动作的具体代码,供大家参考,具体内容如下 这些天依然在看nao公司文档的东西,把读过的代码顺手敲了出来。代码依然很简单,但是为什么我要...

使用python编写udp协议的ping程序方法

服务器端 import random from socket import * serverSocket = socket(AF_INET, SOCK_DGRAM)#建立udp协...

Python pip 安装与使用(安装、更新、删除)

pip 是 Python 包管理工具,该工具提供了对Python 包的查找、下载、安装、卸载的功能。 pip检测更新 命令:pip list –outdated pip升级包 命令...

python打印异常信息的两种实现方式

1. 直接打印错误 try: # your code except KeyboardInterrupt: print("quit") except Excepti...

详解python运行三种方式

方式一 交互式编程 交互式编程不需要创建脚本文件,是通过 Python 解释器的交互模式进来编写代码。 linux上你只需要在命令行中输入 Python 命令即可启动交互式编程,提示窗口...