当前位置: 首页 > news >正文

python笔记基础--文件和存储数据(7)

目录

1.从文件中读取数据

2.写入文件

3.存储数据

3.1使用json.dump()和json.load()

3.2保存和读取用户生成的数据

3.3重构


1.从文件中读取数据

读取整个文件

with open('data.txt') as file_object:
    contents = file_object.read()
print(contents)
print(contents.rstrip()) #删除字符串末尾空白

文件路径

with open('text_files//data.txt') as file_object:

file_path = '/home/eh/data.txy'
with open(file_path) as file_object:

逐行读取

with open(file_path) as file_object:
    for line in file_path:
        print(line.rstrip())

创建一个包含

文件各行内容的列表

filename ='data.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())

使用文件内容

data_string = ''
for line in lines:
    data_string += line.rstrip() #循环加入data_string
print(data_string)

打印圆周率小数点后10位数

3.1415926535…

print(f"{data_string[:12]}")

数列中是否包含这个字段

……

my_data = input("输入数字,字符串是否有这个数:")
if my_data in data_string:
    print("你的数字在这个字符串中")
else:
    print("你的数字不在这个字符串中")

2.写入文件

写入空文件

file = 'abc.txt'
with open(file) as file_object:
    file_object.write("我是一个蘑菇。")

写入多行open(file, 'w')

with open(file, 'w') as file_object:
    file_object.write("我是一个蘑菇。\n")
    file_object.write("我不是一个蘑菇。\n")

附加到文件open(file, 'a')

with open(file, 'a') as file_object:
    file_object.write("我是一个蘑菇。\n")

3.存储数据

json能够将简单的python数据结构转储到文件中

3.1使用json.dump()和json.load()

json.dump()

可以接受两个实参

import json

number =[2,3,5]
filename = 'number.json'
with open(filename, 'w') as f:
    json.dump(number, f)

number.json文件中:

[2, 3, 5]

json.load()

将列表

读取到内存中

with open(filename, 'w') as f:
    numbers = json.load(f)
print(numbers)

3.2保存和读取用户生成的数据

代码

输出

username.json文件

存储用户

import json

username = input("你的名字:")
filename = 'username.json'
with open(filename, 'w') as f:
    json.dump(username, f)
    print(f"Hello,{username}!")

你的名字:Ann

Hello,Ann!

"Ann"

向已存储的用户

发出问候

import json
filename = 'username.json'
with open(filename) as f:
    username = json.load(f)
    print(f"欢迎回来,{username}!")

欢迎回来,Ann!

如用户已存储,加载他。如果没有,则提示用户输入并存储。

import json

filename = 'username.json'
try:
    with open(filename) as f:    #尝试打开username.json
        username = json.load(f)    #如果username.json存在
except FileNotFoundError:    #username.json不存在
    username = input("你的名字:")
    with open(username, 'w') as f:
        json.dump(username, f)    #存储
        print(f"Hello,{username}!")
else:
    print(f"欢迎回来,{username}!")

3.3重构

重构:代码能够正常运行,但通过将其划分为一系列完成具体工作的函数,还可以进行改进。

作用:让代码更清晰、更利于理解、更容易扩展。

http://www.lryc.cn/news/324586.html

相关文章:

  • Vue黑马笔记(最新)
  • 安全工具介绍 SCNR/Arachni
  • 赋能数据收集:从机票网站提取特价优惠的JavaScript技巧
  • 【大模型】在VS Code(Visual Studio Code)上安装中文汉化版插件
  • 自定义WordPress顶部的菜单的方法
  • 独孤思维:流量暴涨,却惨遭违规
  • 【python 装饰器 - 重试】做一个简易重试装饰器,如果函数执行错误则会自动重新执行,可设置重试次数,对爬虫比较友好
  • Linux线程补充之——同步
  • 面试九 设计模式
  • c++和c语言的区别实例
  • 图论基础|841.钥匙和房间、463. 岛屿的周长
  • 把 Taro 项目作为一个完整分包,Taro项目里分包的样式丢失
  • 腾讯云服务器价格查询系统,2024年1年、3年和5年活动价格表
  • 第十四届蓝桥杯大赛软件赛省赛Java大学B组
  • Java二阶知识点总结(七)SVN和Git
  • Java后端八股------设计模式
  • DBO优化GRNN回归预测(matlab代码)
  • Day 31 贪心01
  • C++11特性:std::lock_guard是否会引起死锁?
  • stm32使用定时器实现PWM与呼吸灯
  • MAC本安装telnet
  • [AIGC] 使用Spring Boot进行单元测试:一份指南
  • 使用 Go 语言统计 0-200000 的数字中,哪些是素数?
  • Fabric Measurement
  • wayland(xdg_wm_base) + egl + opengles 使用 Assimp 加载材质文件Mtl 中的纹理图片最简实例(十六)
  • 面试常问:为什么 Vite 速度比 Webpack 快?
  • React腳手架已經創建好了,想使用Vite作為開發依賴
  • 数据结构——双向链表(C语言版)
  • 缓存雪崩、缓存穿透、缓存预热、缓存更新、缓存降级等问题
  • 深度学习pytorch——多层感知机反向传播(持续更新)