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

【学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.dtcms.com/a/362852.html

相关文章:

  • Pandas Python数据处理库:高效处理Excel/CSV数据,支持分组统计与Matplotlib可视化联动
  • 车载刷写架构 --- ECU软件更新怎么保证数据的正确性?
  • Ansible 循环、过滤器与判断逻辑
  • 【保姆级喂饭教程】把chrome谷歌浏览器中的插件导出为CRX安装包
  • Android init 实战项目
  • 文件页的预取逻辑
  • IAM(Identity and Access Management)
  • windows中使用cmd/powershell查杀进程
  • k8s的CRD自定义资源类型示例
  • 从全球视角到K8s落地的Apache IoTDB实战
  • 2025年新版C语言 模电数电及51单片机Proteus嵌入式开发入门实战系统学习,一整套全齐了再也不用东拼西凑
  • AI零售创业公司:零眸智能
  • Elasticsearch 深分页限制与解决方案
  • Flink RuntimeContext和FunctionContext:状态计算的核心桥梁
  • flink中的窗口的介绍
  • uni-app iOS 应用版本迭代与上架实践 持续更新的高效流程
  • Windows远程连接:SSH+RDP+Server
  • 阿里云携手MiniMax构建云原生数仓最佳实践:大模型时代的 Data + AI 数据处理平台
  • 【Python3教程】Python3高级篇之XML解析
  • 消息存储机制-索引文件及页缓存
  • uniapp中输入金额的过滤(只允许输入数字和小数点)
  • Redis分层缓存
  • kukekey在线搭建k8sV1.30.4版本
  • VMWare ubuntu24.04安装(安装ubuntu安装)
  • InnoDB存储引擎-逻辑存储结构
  • Qwen3-30B-A3B 模型解析
  • 【LeetCode牛客数据结构】单链表的应用
  • C语言(长期更新)第12讲:指针二详解
  • 【嵌入式电机控制#进阶6】三段启动法
  • 怎么为服务器设置或重置服务器密码?