8、输入输出方式介绍

书诚小驿2025/03/08Python知识库Python

一、标准输入输出

1、print 函数

# 1. 基本输出
print("Hello, World!")  # 输出: Hello, World!

# 2. 多个值的输出
name = "Python"
age = 30
print(name, age)  # 输出: Python 30

# 3. sep 参数:指定分隔符
print(name, age, sep='-')  # 输出: Python-30

# 4. end 参数:指定结尾符
print("Hello", end='!')
print("World")  # 输出: Hello!World

2、input 函数

# 1. 基本输入
name = input("Please enter your name: ")
print(f"Hello, {name}!")

# 2. 输入类型转换
age = int(input("Enter your age: "))  # 转换为整数
height = float(input("Enter your height: "))  # 转换为浮点数

二、文件输入输出

1、文件的基本操作

# 1. 写入文件
with open('example.txt', 'w', encoding='utf-8') as f:
    f.write("Hello, World!\n")  # 写入单行
    f.writelines(["Line 1\n", "Line 2\n"])  # 写入多行

# 2. 读取文件
with open('example.txt', 'r', encoding='utf-8') as f:
    # 读取整个文件
    content = f.read()
    print(content)
    
    # 读取单行
    f.seek(0)  # 返回文件开头
    line = f.readline()
    print(line)
    
    # 逐行读取
    f.seek(0)
    for line in f:
        print(line, end='')

# 3. 追加模式
with open('example.txt', 'a', encoding='utf-8') as f:
    f.write("\nAppended line")

2、二进制文件操作

# 1. 写入二进制文件
data = bytes([65, 66, 67])  # ABC的ASCII码
with open('binary.bin', 'wb') as f:
    f.write(data)

# 2. 读取二进制文件
with open('binary.bin', 'rb') as f:
    binary_data = f.read()
    print(binary_data)  # 输出: b'ABC'

三、格式化输出

1、字符串格式化

# 1. % 操作符
name = "Python"
age = 30
print("%s is %d years old" % (name, age))  # 输出: Python is 30 years old

# 2. format() 方法
print("{} is {} years old".format(name, age))  # 输出: Python is 30 years old
print("{name} is {age} years old".format(name=name, age=age))  # 命名参数

# 3. f-string (推荐)
print(f"{name} is {age} years old")  # 输出: Python is 30 years old

2、数值格式化

# 1. 整数格式化
num = 42
print(f"{num:03d}")  # 输出: 042 (填充零)
print(f"{num:5d}")   # 输出:    42 (左侧空格)

# 2. 浮点数格式化
pi = 3.14159
print(f"{pi:.2f}")   # 输出: 3.14 (保留两位小数)
print(f"{pi:10.2f}")  # 输出:      3.14 (左侧空格)

# 3. 百分比格式化
ratio = 0.8523
print(f"{ratio:.1%}")  # 输出: 85.2%

3、表格格式化

# 1. 简单表格
data = [
    ["Name", "Age", "City"],
    ["Alice", 25, "Beijing"],
    ["Bob", 30, "Shanghai"]
]

# 打印对齐的表格
for row in data:
    print(f"{row[0]:<10}{row[1]:^5}{row[2]:>10}")

# 输出:
# Name      Age      City
# Alice     25   Beijing
# Bob       30  Shanghai

# 2. 使用 tabulate 模块
from tabulate import tabulate
print(tabulate(data, headers='firstrow', tablefmt='grid'))

四、实用技巧

1、文件路径处理

# 1. 使用 pathlib
from pathlib import Path

# 创建路径对象
path = Path('example.txt')

# 读取文件
content = path.read_text(encoding='utf-8')

# 写入文件
path.write_text("Hello, World!", encoding='utf-8')

# 2. 使用 os.path
import os.path

# 路径拼接
file_path = os.path.join('folder', 'example.txt')

# 检查文件是否存在
if os.path.exists(file_path):
    print("File exists!")

2、异常处理

# 1. 文件操作异常处理
try:
    with open('nonexistent.txt', 'r') as f:
        content = f.read()
except FileNotFoundError:
    print("File not found!")
except IOError as e:
    print(f"IO Error: {e}")

# 2. 输入验证
try:
    age = int(input("Enter your age: "))
    if age < 0:
        raise ValueError("Age cannot be negative!")
except ValueError as e:
    print(f"Invalid input: {e}")