4.2 Python3 输入和输出

Python提供了多种输入输出(I/O)方式,从基本的控制台输入输出到文件操作,再到更高级的数据序列化。


目录

1. 基本输入输出

1.1 print() 函数

1.2 input() 函数

2. 文件操作

2.1 打开文件

2.2 读取文件内容

2.3 文件操作的其他方法

3. 格式化输出

3.1 字符串格式化

3.2 数字格式化

4. 高级I/O操作

4.1 使用StringIO进行内存文件操作

4.2 使用pickle进行对象序列化

4.3 使用json进行数据交换

5. 标准输入输出流

最佳实践


1. 基本输入输出

1.1 print() 函数

print() 是 Python 中最基本的输出函数,用于将内容输出到标准输出(通常是控制台)。

基本语法

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

常用功能

  1. 基本输出

    print("Hello, World!")  # 输出: Hello, World!
  2. 输出多个值

    print("Python", 3.9, "is awesome!")  # 输出: Python 3.9 is awesome!
  3. 修改分隔符(sep参数)

    print("2023", "03", "15", sep="-")  # 输出: 2023-03-15
  4. 修改结束符(end参数)

    print("Hello", end=" ")
    print("World!")  # 输出: Hello World!
  5. 输出到文件

    with open('output.txt', 'w') as f:
        print("This goes to a file", file=f)
  6. 格式化输出

    name = "Alice"
    age = 25
    print(f"{name} is {age} years old.")  # f-string (Python 3.6+)
    print("{} is {} years old.".format(name, age))  # format方法

1.2 input() 函数

input() 函数用于从标准输入(通常是键盘)获取用户输入。

基本语法

input([prompt])  # prompt是可选的提示信息

常用功能

  1. 基本输入

    name = input("请输入你的名字: ")
    print(f"你好, {name}!")
  2. 输入类型转换

    age = int(input("请输入你的年龄: "))  # 转换为整数
    price = float(input("请输入价格: "))  # 转换为浮点数
  3. 多值输入

    # 输入多个值用空格分隔
    values = input("请输入多个数字(空格分隔): ").split()
    numbers = [int(x) for x in values]
  4. 输入验证

    while True:
        try:
            age = int(input("请输入年龄(1-120): "))
            if 1 <= age <= 120:
                break
            else:
                print("请输入有效年龄!")
        except ValueError:
            print("请输入数字!")

2. 文件操作

2.1 打开文件

# 基本语法: open(filename, mode)
# 模式: 
#   'r' - 读取 (默认)
#   'w' - 写入 (会覆盖已有文件)
#   'a' - 追加
#   'x' - 创建新文件
#   'b' - 二进制模式
#   't' - 文本模式 (默认)
#   '+' - 读写模式

# 推荐使用with语句,自动关闭文件
with open('example.txt', 'w', encoding='utf-8') as f:
    f.write("这是第一行\n")
    f.write("这是第二行\n")

2.2 读取文件内容

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

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

# 读取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    print(lines)

2.3 文件操作的其他方法

# 检查文件是否存在
import os
if os.path.exists('example.txt'):
    print("文件存在")

# 获取文件大小
size = os.path.getsize('example.txt')
print(f"文件大小: {size}字节")

# 重命名文件
os.rename('example.txt', 'new_example.txt')

# 删除文件
os.remove('new_example.txt')

3. 格式化输出

3.1 字符串格式化

# 使用f-string (Python 3.6+)
name = "Alice"
age = 25
print(f"{name} is {age} years old.")

# 使用format()方法
print("{} is {} years old.".format(name, age))

# 使用%格式化 (旧式)
print("%s is %d years old." % (name, age))

3.2 数字格式化

pi = 3.1415926535

# 保留2位小数
print(f"π的值是: {pi:.2f}")  # 输出: π的值是: 3.14

# 科学计数法
print(f"{pi:.2e}")  # 输出: 3.14e+00

# 百分比
score = 0.8567
print(f"正确率: {score:.1%}")  # 输出: 正确率: 85.7%

4. 高级I/O操作

4.1 使用StringIO进行内存文件操作

python

from io import StringIO

# 创建一个内存中的文件对象
memory_file = StringIO()
memory_file.write("内存中的第一行\n")
memory_file.write("内存中的第二行\n")

# 读取内容
memory_file.seek(0)  # 将指针移到文件开头
print(memory_file.read())

4.2 使用pickle进行对象序列化

pickle 是 Python 的一个强大序列化模块,它可以将几乎任何 Python 对象转换为字节流(序列化),也可以从字节流重新构造对象(反序列化)。

import pickle

data = {'name': 'Alice', 'age': 25, 'scores': [88, 92, 95]}

# 序列化到文件
with open('data.pkl', 'wb') as f:  # 注意是二进制模式
    pickle.dump(data, f)

# 从文件反序列化
with open('data.pkl', 'rb') as f:
    loaded_data = pickle.load(f)
    print(loaded_data)

4.3 使用json进行数据交换

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,Python 提供了 json 模块来处理 JSON 数据。

import json

data = {'name': 'Alice', 'age': 25, 'scores': [88, 92, 95]}

# 写入JSON文件
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=4)  # indent参数美化输出

# 读取JSON文件
with open('data.json', 'r', encoding='utf-8') as f:
    loaded_data = json.load(f)
    print(loaded_data)

5. 标准输入输出流

import sys

# 写入标准错误
sys.stderr.write("这是一个错误消息\n")

# 从标准输入读取
for line in sys.stdin:  # 按Ctrl+D(Unix)或Ctrl+Z(Windows)结束输入
    print(f"你输入了: {line.strip()}")

最佳实践

  1. 总是明确指定文件编码(推荐UTF-8)

  2. 使用with语句处理文件,确保文件正确关闭

  3. 处理文件时考虑异常情况(如文件不存在)

  4. 大文件使用逐行读取或分块读取,避免内存问题

  5. 敏感数据避免使用pickle,考虑更安全的序列化方式如json


Python的I/O系统非常强大,掌握这些基本操作可以应对大多数数据处理需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值