Skip to content

Python 输入和输出

在 Python 中,输入和输出是与用户交互的重要方式。本章节将详细介绍 Python 中的输入和输出操作,包括标准输入/输出、文件输入/输出以及格式化输出等内容。

标准输出(print 函数)

print() 函数是 Python 中最常用的输出函数,用于将内容打印到控制台。

基本语法

python
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

参数说明

  • value:要打印的值(可以是多个)
  • sep:多个值之间的分隔符,默认为空格
  • end:打印结束后的字符,默认为换行符
  • file:输出文件对象,默认为标准输出
  • flush:是否立即刷新缓冲区,默认为 False

示例

python
# 基本输出
print("Hello, World!")

# 多个值
print("Hello", "World", "!")

# 自定义分隔符
print("Hello", "World", "!", sep=", ")

# 自定义结束符
print("Hello", end=" ")
print("World!")

# 打印变量
name = "Alice"
age = 30
print("Name:", name, "Age:", age)

# 打印表达式
print("1 + 2 =", 1 + 2)

# 打印到文件
with open("output.txt", "w") as f:
    print("Hello, File!", file=f)

输出结果

Hello, World!
Hello World !
Hello, World, !
Hello World!
Name: Alice Age: 30
1 + 2 = 3

标准输入(input 函数)

input() 函数用于从控制台读取用户输入的内容。

基本语法

python
input(prompt=None)

参数说明

  • prompt:提示信息,可选

示例

python
# 基本输入
name = input("请输入你的名字:")
print(f"你好,{name}!")

# 输入数字
age = input("请输入你的年龄:")
print(f"你的年龄是:{age}")
print(f"年龄类型:{type(age)}")

# 输入转换为数字
age = int(input("请输入你的年龄:"))
print(f"你的年龄是:{age}")
print(f"年龄类型:{type(age)}")

# 输入多个值
values = input("请输入两个数字,用空格分隔:").split()
x = int(values[0])
y = int(values[1])
print(f"两个数字的和:{x + y}")

# 异常处理
while True:
    try:
        number = int(input("请输入一个数字:"))
        print(f"你输入的数字是:{number}")
        break
    except ValueError:
        print("错误:请输入有效的数字!")

运行示例

请输入你的名字:Alice
你好,Alice!
请输入你的年龄:30
你的年龄是:30
年龄类型:<class 'str'>
请输入你的年龄:30
你的年龄是:30
年龄类型:<class 'int'>
请输入两个数字,用空格分隔:5 10
两个数字的和:15
请输入一个数字:abc
错误:请输入有效的数字!
请输入一个数字:123
你输入的数字是:123

格式化输出

Python 提供了多种格式化输出的方法,包括:

  1. 格式化字符串字面量(f-strings,Python 3.6+)
  2. str.format() 方法
  3. 格式化操作符 %

1. 格式化字符串字面量(f-strings)

f-strings 是 Python 3.6+ 中引入的一种格式化字符串的方法,使用 fF 前缀,在字符串中使用 {} 包含表达式。

示例

python
# 基本用法
name = "Alice"
age = 30
print(f"我的名字是 {name},年龄是 {age} 岁。")

# 表达式
x = 10
y = 20
print(f"{x} + {y} = {x + y}")

# 函数调用
print(f"{name.upper()} 是我的名字的大写形式。")

# 格式化数字
pi = 3.1415926
print(f"π 的值约为 {pi:.2f}。")  # 保留两位小数
print(f"π 的值约为 {pi:.4f}。")  # 保留四位小数

# 格式化宽度
print(f"{name:10} 年龄: {age:5}")
print(f"{name:>10} 年龄: {age:<5}")  # 右对齐和左对齐

# 格式化日期
from datetime import datetime
now = datetime.now()
print(f"当前时间: {now:%Y-%m-%d %H:%M:%S}")

# 嵌套表达式
items = [1, 2, 3]
print(f"列表长度: {len(items)}, 列表内容: {items}")

# 条件表达式
status = True
print(f"状态: {'在线' if status else '离线'}")

输出结果

我的名字是 Alice,年龄是 30 岁。
10 + 20 = 30
ALICE 是我的名字的大写形式。
π 的值约为 3.14。
π 的值约为 3.1416。
Alice      年龄:    30
     Alice 年龄: 30   
当前时间: 2024-01-01 12:00:00
列表长度: 3, 列表内容: [1, 2, 3]
状态: 在线

2. str.format() 方法

str.format() 方法使用 {} 作为占位符,用于格式化字符串。

基本语法

python
"字符串模板".format(value, ...)

示例

python
# 基本用法
print("我的名字是 {},年龄是 {} 岁。".format("Alice", 30))

# 位置参数
print("{} + {} = {}".format(10, 20, 10 + 20))

# 关键字参数
print("我的名字是 {name},年龄是 {age} 岁。".format(name="Alice", age=30))

# 混合使用
print("{} 的年龄是 {age} 岁。".format("Alice", age=30))

# 格式化数字
pi = 3.1415926
print("π 的值约为 {:.2f}。".format(pi))
print("π 的值约为 {:.4f}。".format(pi))

# 格式化宽度
name = "Alice"
age = 30
print("{:10} 年龄: {:5}".format(name, age))
print("{:>10} 年龄: {:<5}".format(name, age))

# 格式化日期
from datetime import datetime
now = datetime.now()
print("当前时间: {:%Y-%m-%d %H:%M:%S}".format(now))

# 访问对象属性
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 30)
print("{} 的年龄是 {} 岁。".format(person.name, person.age))
print("{0.name} 的年龄是 {0.age} 岁。".format(person))

# 访问字典值
person_dict = {"name": "Alice", "age": 30}
print("{name} 的年龄是 {age} 岁。".format(**person_dict))

输出结果

我的名字是 Alice,年龄是 30 岁。
10 + 20 = 30
我的名字是 Alice,年龄是 30 岁。
Alice 的年龄是 30 岁。
π 的值约为 3.14。
π 的值约为 3.1416。
Alice      年龄:    30
     Alice 年龄: 30   
当前时间: 2024-01-01 12:00:00
Alice 的年龄是 30 岁。
Alice 的年龄是 30 岁。
Alice 的年龄是 30 岁。

3. 格式化操作符 %

格式化操作符 % 是一种传统的格式化字符串的方法,类似于 C 语言中的 printf 函数。

基本语法

python
"字符串模板" % (value, ...)

格式说明符

格式说明符描述
%s字符串
%d十进制整数
%f浮点数
%e科学计数法
%x十六进制整数
%o八进制整数
%%百分号

示例

python
# 基本用法
print("我的名字是 %s,年龄是 %d 岁。" % ("Alice", 30))

# 多个值
print("%d + %d = %d" % (10, 20, 10 + 20))

# 格式化浮点数
pi = 3.1415926
print("π 的值约为 %f。" % pi)
print("π 的值约为 %.2f。" % pi)  # 保留两位小数
print("π 的值约为 %.4f。" % pi)  # 保留四位小数

# 格式化宽度
name = "Alice"
age = 30
print("%-10s 年龄: %5d" % (name, age))  # 左对齐
print("%10s 年龄: %-5d" % (name, age))  # 右对齐

# 混合使用
print("%s 的年龄是 %d 岁,身高是 %.2f 米。" % ("Alice", 30, 1.65))

# 格式化字典
person_dict = {"name": "Alice", "age": 30}
print("%(name)s 的年龄是 %(age)d 岁。" % person_dict)

# 格式化二进制、八进制、十六进制
number = 42
print("十进制: %d" % number)
print("二进制: %b" % number)
print("八进制: %o" % number)
print("十六进制: %x" % number)
print("十六进制(大写): %X" % number)

# 格式化科学计数法
number = 123456789
print("科学计数法: %e" % number)
print("科学计数法(保留两位小数): %.2e" % number)

输出结果

我的名字是 Alice,年龄是 30 岁。
10 + 20 = 30
π 的值约为 3.141593。
π 的值约为 3.14。
π 的值约为 3.1416。
Alice      年龄:    30
     Alice 年龄: 30   
Alice 的年龄是 30 岁,身高是 1.65 米。
Alice 的年龄是 30 岁。
十进制: 42
二进制: 101010
八进制: 52
十六进制: 2a
十六进制(大写): 2A
科学计数法: 1.234568e+08
科学计数法(保留两位小数): 1.23e+08

文件输入/输出

文件输入/输出是 Python 中处理文件的重要方式,包括读取文件和写入文件。

文件写入

python
# 写入文件
with open("example.txt", "w", encoding="utf-8") as f:
    f.write("Hello, File!\n")
    f.write("This is a test.\n")
    f.write("Python file I/O.\n")

# 追加内容
with open("example.txt", "a", encoding="utf-8") as f:
    f.write("Appended content.\n")

# 写入多行
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("lines.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)

文件读取

python
# 读取整个文件
with open("example.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print("读取整个文件:")
    print(content)

# 逐行读取
with open("example.txt", "r", encoding="utf-8") as f:
    print("逐行读取:")
    for line in f:
        print(line.strip())

# 读取所有行
with open("example.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    print("读取所有行:")
    print(lines)
    print("处理后:")
    for line in lines:
        print(line.strip())

# 读取指定字节
with open("example.txt", "r", encoding="utf-8") as f:
    content = f.read(10)  # 读取前 10 个字符
    print("读取指定字节:")
    print(content)

二进制文件操作

python
# 写入二进制文件
data = b"Hello, Binary!"
with open("binary.bin", "wb") as f:
    f.write(data)

# 读取二进制文件
with open("binary.bin", "rb") as f:
    content = f.read()
    print("读取二进制文件:")
    print(content)
    print("解码后:")
    print(content.decode("utf-8"))

高级输入/输出技巧

1. 使用 sys 模块

sys 模块提供了对 Python 解释器相关的操作,包括标准输入/输出。

python
import sys

# 标准输出
sys.stdout.write("Hello, sys.stdout!\n")

# 标准错误
sys.stderr.write("Hello, sys.stderr!\n")

# 命令行参数
print("命令行参数:", sys.argv)

# 退出程序
sys.exit(0)  # 正常退出
sys.exit(1)  # 异常退出

2. 使用 io 模块

io 模块提供了对 I/O 操作的更高级抽象。

python
import io

# 字符串缓冲区
buffer = io.StringIO()
buffer.write("Hello, StringIO!\n")
buffer.write("This is a test.\n")

# 读取缓冲区内容
buffer.seek(0)  # 移动到缓冲区开头
content = buffer.read()
print("字符串缓冲区内容:")
print(content)

# 二进制缓冲区
binary_buffer = io.BytesIO()
binary_buffer.write(b"Hello, BytesIO!")

# 读取二进制缓冲区内容
binary_buffer.seek(0)
binary_content = binary_buffer.read()
print("二进制缓冲区内容:")
print(binary_content)

3. 进度条

python
import time

# 简单进度条
def progress_bar(total, current):
    bar_length = 50
    progress = current / total
    filled_length = int(bar_length * progress)
    bar = '=' * filled_length + '-' * (bar_length - filled_length)
    percentage = progress * 100
    print(f'[{bar}] {percentage:.1f}%', end='\r')

# 测试进度条
print("下载进度:")
total_size = 1000
for i in range(total_size + 1):
    progress_bar(total_size, i)
    time.sleep(0.001)
print()
print("下载完成!")

4. 彩色输出

使用 ANSI 转义序列实现彩色输出:

python
# 彩色输出
class Colors:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    MAGENTA = '\033[95m'
    CYAN = '\033[96m'
    WHITE = '\033[97m'
    RESET = '\033[0m'

# 测试彩色输出
print(f"{Colors.RED}红色文本{Colors.RESET}")
print(f"{Colors.GREEN}绿色文本{Colors.RESET}")
print(f"{Colors.YELLOW}黄色文本{Colors.RESET}")
print(f"{Colors.BLUE}蓝色文本{Colors.RESET}")
print(f"{Colors.MAGENTA}洋红色文本{Colors.RESET}")
print(f"{Colors.CYAN}青色文本{Colors.RESET}")
print(f"{Colors.WHITE}白色文本{Colors.RESET}")

# 组合使用
print(f"{Colors.RED}错误:{Colors.RESET} 发生了一个错误")
print(f"{Colors.GREEN}成功:{Colors.RESET} 操作成功完成")
print(f"{Colors.YELLOW}警告:{Colors.RESET} 这是一个警告")
print(f"{Colors.BLUE}信息:{Colors.RESET} 这是一条信息")

总结

Python 提供了丰富的输入和输出功能,包括:

  1. 标准输出print() 函数,用于将内容打印到控制台
  2. 标准输入input() 函数,用于从控制台读取用户输入
  3. 格式化输出
    • 格式化字符串字面量(f-strings,Python 3.6+)
    • str.format() 方法
    • 格式化操作符 %
  4. 文件输入/输出
    • 文本文件操作
    • 二进制文件操作
  5. 高级技巧
    • 使用 sys 模块
    • 使用 io 模块
    • 进度条
    • 彩色输出

掌握这些输入和输出技巧,对于编写交互式程序、处理文件和调试代码都非常重要。