Python 输入输出
在编程中,输入和输出是与用户和外部世界交互的基础。Python提供了多种简单易用的方式来处理输入输出操作,这些操作对于从简单的命令行程序到复杂的数据处理应用都至关重要。
标准输入输出
输出数据: print()
函数
print()
函数是Python中最常用的输出方法,它可以将数据显示在屏幕上。
基本用法
python
print("Hello, World!") # 输出字符串
print(42) # 输出数字
print(True) # 输出布尔值
# 输出多个值
print("姓名:", "张三", "年龄:", 25)
# 输出结果
# Hello, World!
# 42
# True
# 姓名: 张三 年龄: 25
格式化输出参数
print()
函数有几个实用的参数可以控制输出格式:
python
# sep参数: 设置分隔符
print("苹果", "香蕉", "橙子", sep=", ") # 苹果, 香蕉, 橙子
# end参数: 设置结束符
print("不换行", end=" >>> ")
print("在同一行") # 不换行 >>> 在同一行
# file参数: 输出到文件
import sys
print("输出到标准错误流", file=sys.stderr)
输入数据: input()
函数
input()
函数用于从用户那里获取输入,它总是返回一个字符串。
python
name = input("请输入您的姓名: ")
print("您好,", name)
# 如果需要获取数值,需要进行类型转换
age = int(input("请输入您的年龄: "))
height = float(input("请输入您的身高(米): "))
print(f"您今年{age}岁,身高{height}米")
# 示例输出:
# 请输入您的姓名: 李四
# 您好, 李四
# 请输入您的年龄: 28
# 请输入您的身高(米): 1.75
# 您今年28岁,身高1.75米
注意
使用input()
获取数值时,一定要记得进行类型转换,因为input()
始终返回字符串。如果用户输入的不是有效数值,类型转换将会引发ValueError
异常。
字符串格式化
Python提供了多种字符串格式化的方式,允许我们将变量值嵌入到字符串中。
f-字符串 (Python 3.6+)
这是最现代、最推荐的字符串格式化方法:
python
name = "王五"
age = 30
height = 1.80
print(f"姓名: {name}, 年龄: {age}, 身高: {height:.2f}米")
# 姓名: 王五, 年龄: 30, 身高: 1.80米
format()方法
python
name = "赵六"
age = 35
print("姓名: {}, 年龄: {}".format(name, age))
# 姓名: 赵六, 年龄: 35
# 使用索引
print("姓名: {0}, 年龄: {1}. {0}今年{1}岁了".format(name, age))
# 姓名: 赵六, 年龄: 35. 赵六今年35岁了
# 使用命名参数
print("姓名: {name}, 年龄: {age}".format(name="钱七", age=40))
# 姓名: 钱七, 年龄: 40
%-格式化 (传统方式)
python
name = "孙八"
age = 45
print("姓名: %s, 年龄: %d" % (name, age))
# 姓名: 孙八, 年龄: 45
# 格式化浮点数
pi = 3.14159
print("π值约等于: %.2f" % pi) # π值约等于: 3.14
文件输入输出
打开和关闭文件
Python使用open()
函数打开文件,该函数返回一个文件对象,通过这个对象可以对文件进行各种操作。
python
# 打开文件进行读取 (默认模式)
file = open("example.txt", "r")
content = file.read()
file.close() # 重要:使用完文件后务必关闭
# 更安全的方式是使用with语句,它会自动关闭文件
with open("example.txt", "r") as file:
content = file.read()
# 文件会在离开with语句块时自动关闭
文件打开模式
模式 | 描述 |
---|---|
'r' | 只读模式(默认) |
'w' | 写入模式(会覆盖已有内容) |
'a' | 追加模式(在文件末尾添加内容) |
'r+' | 读写模式 |
'b' | 二进制模式(与其他模式结合使用,如'rb'或'wb') |
文件读取操作
python
with open("example.txt", "r", encoding="utf-8") as file:
# 读取整个文件
content = file.read()
print("全部内容:", content)
with open("example.txt", "r", encoding="utf-8") as file:
# 逐行读取
for line in file:
print("这一行:", line.strip()) # strip()移除首尾空白字符
with open("example.txt", "r", encoding="utf-8") as file:
# 读取特定行数
lines = file.readlines() # 返回一个包含所有行的列表
print("第一行:", lines[0].strip())
print("总行数:", len(lines))
提示
在处理文本文件时,请始终指定encoding
参数,特别是当文件包含非ASCII字符时。UTF-8是处理多语言文本的良好选择。
文件写入操作
python
# 写入模式(覆盖已有内容)
with open("output.txt", "w", encoding="utf-8") as file:
file.write("这是第一行\n")
file.write("这是第二行\n")
# 写入多行
lines = ["第三行\n", "第四行\n", "第五行\n"]
file.writelines(lines)
# 追加模式
with open("output.txt", "a", encoding="utf-8") as file:
file.write("这行将添加到文件末尾\n")
实际应用案例
案例1: 简单的记事本程序
这个程序允许用户输入笔记并保存到文件中:
python
def take_notes():
print("欢迎使用简易记事本!")
filename = input("请输入保存文件名: ")
# 确保文件名有.txt后缀
if not filename.endswith(".txt"):
filename += ".txt"
print("请输入您的笔记内容(输入'完成'单独一行表示结束):")
lines = []
while True:
line = input()
if line == "完成":
break
lines.append(line + "\n")
# 写入文件
with open(filename, "w", encoding="utf-8") as file:
file.writelines(lines)
print(f"笔记已保存到 {filename}!")
# 运行程序
take_notes()
案例2: 简单的数据分析
读取包含数字的文件并计算平均值:
python
def analyze_numbers(filename):
numbers = []
try:
with open(filename, "r") as file:
for line in file:
try:
# 尝试将每行转换为浮点数
num = float(line.strip())
numbers.append(num)
except ValueError:
# 忽略无法转换的行
print(f"警告: 忽略无效的行: '{line.strip()}'")
# 分析数据
if numbers:
total = sum(numbers)
average = total / len(numbers)
maximum = max(numbers)
minimum = min(numbers)
print(f"分析结果:")
print(f"数据点数量: {len(numbers)}")
print(f"总和: {total}")
print(f"平均值: {average:.2f}")
print(f"最大值: {maximum}")
print(f"最小值: {minimum}")
else:
print("未找到有效数据!")
except FileNotFoundError:
print(f"错误: 文件 '{filename}' 不存在!")
# 示例调用
analyze_numbers("data.txt")
JSON数据的输入输出
JSON (JavaScript Object Notation) 是一种常用的数据交换格式。Python的json
模块提供了处理JSON数据的功能:
python
import json
# 将Python对象转换为JSON字符串
student = {
"name": "张明",
"age": 20,
"courses": ["Python", "数据库", "网络编程"],
"is_active": True,
"scores": {"Python": 95, "数据库": 89}
}
# 转换为JSON字符串
json_str = json.dumps(student, ensure_ascii=False, indent=4)
print("JSON字符串:")
print(json_str)
# 写入JSON文件
with open("student.json", "w", encoding="utf-8") as file:
json.dump(student, file, ensure_ascii=False, indent=4)
# 从JSON字符串读取
student_copy = json.loads(json_str)
print("\n从字符串恢复的对象:")
print(student_copy["name"], "年龄:", student_copy["age"])
# 从JSON文件读取
with open("student.json", "r", encoding="utf-8") as file:
student_from_file = json.load(file)
print("\n从文件读取的对象:")
print(student_from_file["name"], "的课程:", student_from_file["courses"])
提示
使用ensure_ascii=False
参数可以保持中文字符的可读性,而不是将其转换为Unicode转义序列。
标准输入输出重定向
Python允许临时重定向标准输入输出流:
python
import sys
from io import StringIO
# 保存原始stdout
original_stdout = sys.stdout
# 将输出重定向到一个StringIO对象
fake_output = StringIO()
sys.stdout = fake_output
# 现在print输出到fake_output而不是屏幕
print("这行不会显示在屏幕上")
print("但会被捕获到StringIO对象中")
# 恢复原始stdout
sys.stdout = original_stdout
# 获取捕获的输出
captured_output = fake_output.getvalue()
print("捕获的输出是:")
print(captured_output)
总结
Python的输入输出操作为我们提供了与用户交互和处理文件数据的强大工具:
- 标准输入输出:
print()
和input()
函数是最基本的交互方式 - 字符串格式化: f-字符串、
format()
方法和%-格式化提供了灵活的文本处理能力 - 文件操作: 通过
open()
函数和相关方法可以读写文件 - JSON处理:
json
模块使得处理JSON数据变得简单
掌握这些技术将使您能够创建与用户交互的程序、处理各种数据文件以及进行数据交换和持久化存储。
练习
- 创建一个程序,提示用户输入多个学生的姓名和成绩,然后将这些信息保存到文件中。
- 编写一个程序,从前一个练习创建的文件中读取学生信息,计算平均分并找出最高分的学生。
- 开发一个简单的通讯录程序,允许用户添加、查看和删除联系人,并将数据保存为JSON格式。
- 创建一个日志记录器,能够记录程序运行时的信息,包括时间戳和消息内容。
进一步学习资源
- Python官方文档:Input and Output
- Python IO模块:io — Core tools for working with streams
- JSON模块:json — JSON encoder and decoder
通过掌握这些输入输出技术,你将能够使你的Python程序与外部世界进行有效的交互和通信。