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

【学Python自动化】 7. Python 输入与输出学习笔记

一、更复杂的输出格式

三种输出方式

  • 表达式语句:直接写变量或表达式

  • print() 函数:最常用的输出方式

  • 文件对象的 write() 方法:输出到文件

1 格式化字符串字面值 (f-strings) - 推荐使用

# 基本用法
year = 2016
event = 'Referendum'
print(f'Results of the {year} {event}')  # Results of the 2016 Referendum# 格式控制
import math
print(f'Pi is approximately {math.pi:.3f}')  # Pi is approximately 3.142# 对齐和宽度
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():print(f'{name:10} ==> {phone:10d}')
# Sjoerd     ==>       4127
# Jack       ==>       4098
# Dcab       ==>       7678# 转换修饰符
animals = 'eels'
print(f'My hovercraft is full of {animals!r}')  # My hovercraft is full of 'eels'# 调试用法 (Python 3.8+)
bugs = 'roaches'
count = 13
print(f'{bugs=} {count=}')  # bugs='roaches' count=13
2 字符串 format() 方法

# 位置参数
print('{0} and {1}'.format('spam', 'eggs'))  # spam and eggs
print('{1} and {0}'.format('spam', 'eggs'))  # eggs and spam# 关键字参数
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))# 混合使用
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))# 数字格式化
yes_votes = 42_572_654
total_votes = 85_705_149
percentage = yes_votes / total_votes
print('{:-9} YES votes {:2.2%}'.format(yes_votes, percentage))
# 42572654 YES votes 49.67%# 表格格式化
for x in range(1, 11):print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
3 手动格式化字符串

# 字符串对齐方法
print('12'.rjust(5))      # '   12' - 右对齐
print('12'.ljust(5))      # '12   ' - 左对齐  
print('12'.center(5))     # ' 12  ' - 居中
print('12'.zfill(5))      # '00012' - 填充零# 手动创建表格
for x in range(1, 11):print(repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4))
4 旧式字符串格式化 (% 操作符)

# 基本用法
import math
print('The value of pi is approximately %5.3f.' % math.pi)# 多个值
name = 'John'
age = 25
print('Name: %s, Age: %d' % (name, age))

str() vs repr()


s = 'Hello, world.'
print(str(s))   # Hello, world. - 给人阅读
print(repr(s))  # 'Hello, world.' - 给解释器阅读hello = 'hello, world\n'
print(repr(hello))  # 'hello, world\n' - 显示转义字符

二、读写文件

文件打开模式

模式描述说明
‘r’读取(默认)文件必须存在
‘w’写入创建新文件或覆盖现有文件
‘a’追加在文件末尾添加内容
‘r+’读写文件必须存在
‘b’二进制模式与上述模式组合使用

推荐的文件操作方式


# 使用 with 语句自动关闭文件
with open('workfile', 'r', encoding='utf-8') as f:read_data = f.read()
print(f.closed)  # True - 文件已自动关闭# 读取文件内容的不同方式
with open('file.txt', 'r') as f:content = f.read()       # 读取整个文件line = f.readline()      # 读取一行lines = f.readlines()    # 读取所有行到列表# 逐行读取(内存高效)
with open('file.txt', 'r') as f:for line in f:print(line, end='')  # 逐行处理

文件写入操作


# 文本写入
with open('output.txt', 'w', encoding='utf-8') as f:f.write('Hello, world!\n')f.write('Second line\n')# 写入其他类型需要先转换
values = ('the answer', 42)
with open('data.txt', 'w') as f:f.write(str(values))  # 转换为字符串

文件定位


# 二进制模式下的文件定位
with open('workfile', 'rb+') as f:f.write(b'0123456789abcdef')f.seek(5)       # 移动到第6个字节print(f.read(1))  # b'5'f.seek(-3, 2)   # 移动到倒数第3个字节print(f.read(1))  # b'd'
2 使用 json 保存结构化数据

JSON 基本操作


import json# Python 对象 → JSON 字符串
x = [1, 'simple', 'list']
json_string = json.dumps(x)  # '[1, "simple", "list"]'# JSON 字符串 → Python 对象
x = json.loads(json_string)  # [1, 'simple', 'list']# 文件操作
data = {'name': 'John', 'age': 30, 'cities': ['New York', 'Paris']}# 写入文件
with open('data.json', 'w', encoding='utf-8') as f:json.dump(data, f)# 从文件读取
with open('data.json', 'r', encoding='utf-8') as f:loaded_data = json.load(f)

JSON 与 Python 类型对应

JSON 类型Python 类型
objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone

三、⚡ 重要注意事项

文件操作最佳实践

  1. 总是使用 with 语句:确保文件正确关闭

  2. 指定编码:特别是文本文件,推荐 encoding=‘utf-8’

  3. 二进制文件用 ‘b’ 模式:如图片、视频等

  4. 大文件逐行处理:避免内存不足

格式化选择建议

  • 现代代码:使用 f-strings(最简洁)

  • 兼容旧版本:使用 str.format()

  • 避免使用:% 操作符(旧式)

JSON 使用场景

  • 配置文件:程序设置和配置

  • 数据交换:API 通信和数据传输

  • 数据持久化:简单数据结构存储

四、💡 实用技巧

上下文管理器多个文件


# 同时处理多个文件
with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:for line in infile:outfile.write(line.upper())

JSON 美化输出


data = {'name': 'John', 'age': 30, 'cities': ['New York', 'Paris']}
pretty_json = json.dumps(data, indent=4, ensure_ascii=False)
# {
#     "name": "John",
#     "age": 30,
#     "cities": [
#         "New York",
#         "Paris"
#     ]
# }

文件存在检查


import osif os.path.exists('file.txt'):with open('file.txt', 'r') as f:content = f.read()
else:print("文件不存在")

这个笔记涵盖了 Python 输入输出的核心概念,从简单的打印到复杂的文件操作和数据序列化!

http://www.xdnf.cn/news/19638.html

相关文章:

  • kaggle中的2D目标检测训练trick总结
  • 用了企业微信 AI 半年,这 5 个功能让我彻底告别重复劳动
  • 一文带你入门 AT 指令集:从串口通信到模块控制
  • 【智能体开发】怎样提升AI智能体的运行速度?
  • 实验2-代理模式和观察者模式设计
  • C++全局变量未初始的和已初始化的位置放在哪里?
  • C语言————实战项目“扫雷游戏”(完整代码)
  • 【Spring Cloud微服务】9.一站式掌握 Seata:架构设计与 AT、TCC、Saga、XA 模式选型指南
  • MD5加密算法详解与实现
  • 【LeetCode_26】删除有序数组中的重复项
  • 手撕Redis底层2-网络模型深度剖析
  • 云电脑是什么?与普通电脑的区别在哪里?——天翼云电脑体验推荐
  • 全国产FT-M6678核心板
  • SQL JOIN 操作全面解析
  • 哈希表-面试题01.02.判定是否互为字符重排-力扣(LeetCode)
  • 【LeetCode数据结构】栈和队列的应用
  • 在windows平台oracle 23ai 数据库上使用bbed
  • 面阵 vs 线阵相机:怎么选不踩坑?选型公式直接套用
  • SQLShift 实现Oracle 到 OceanBase 的存储过程转换初体验
  • 【Vue2 ✨】 Vue2 入门之旅(六):指令与过滤器
  • 阿里云和华为云Rocky LINUX 9.X镜像就绪及低端可用英伟达GPU
  • Google NotebookLM最强替代品评测:AI笔记、语音生成与高效知识管理工具盘点
  • 【Linux基础知识系列:第一百一十八篇】使用perf进行性能分析
  • Day33 网络编程:OSI/TCP/IP模型、协议族与UDP编程
  • 【新启航】3D 逆向抄数的三维能力架构:数据采集工具操作 × 几何处理算法应用 × 行业场景适配技能
  • 微硕WINSOK大功率MOS管 WSF3085在汽车关键系统中的创新应用
  • 【世纪龙科技】汽车专业数字化课程资源包-虚拟仿真实训资源建设
  • 2025大学生必考互联网行业证书排名​
  • Nginx 全攻略:从部署到精通的实战指南(CentOS 环境)
  • 腾讯混元世界模型Voyager开源:单图生成3D世界的“核弹级”突破,游戏、VR、自动驾驶迎来新变量