【学Python自动化】 7.1 Python 与 Rust 输入输出对比学习笔记

发布于:2025-09-03 ⋅ 阅读:(14) ⋅ 点赞:(0)

一、输出格式化对比

字符串格式化方法对比

格式化方式 Python Rust
f-字符串 f"Value: {value}" format!(“Value: {}”, value)
位置参数 “{} {}”.format(a, b) format!(“{} {}”, a, b)
命名参数 “{name} {age}”.format(name=“Alice”, age=30) format!(“{name} {age}”, name=“Alice”, age=30)
数字格式化 f"{number:08x}" format!(“{:08x}”, number)
1 f-字符串 vs format! 宏

Python f-字符串:


name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
# 格式化控制
import math
print(f"Pi: {math.pi:.3f}")  # Pi: 3.142

Rust format! 宏:


let name = "Alice";
let age = 30;
println!("Name: {}, Age: {}", name, age);
// 格式化控制
use std::f64::consts::PI;
println!("Pi: {:.3}", PI);  // Pi: 3.142
2 调试输出对比

Python repr() vs str():


s = "Hello\nWorld"
print(str(s))   # Hello World
print(repr(s))  # 'Hello\nWorld'

value = ("answer", 42)
print(repr(value))  # ('answer', 42)

Rust Debug vs Display trait:


let s = "Hello\nWorld";
println!("{}", s);        // Hello World
println!("{:?}", s);      // "Hello\nWorld"

let value = ("answer", 42);
println!("{:?}", value);  // ("answer", 42)

二、文件操作对比

文件打开模式对比
| 模式 | Python | Rust |
| 读取 | open(“file.txt”, “r”) | File::open(“file.txt”) |
| 写入 | open(“file.txt”, “w”) | File::create(“file.txt”) |
| 追加 | open(“file.txt”, “a”) | OpenOptions::new().append(true) |
| 读写 | open(“file.txt”, “r+”) | OpenOptions::new().read(true).write(true) |
| 二进制 | open(“file.bin”, “rb”) | File::open(“file.bin”) |

1 文件读写基本操作

Python (推荐使用 with):


# 读取文件
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()
    # 或者逐行读取
    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")

Rust (使用 ? 处理错误):


use std::fs::File;
use std::io::{Read, Write, BufReader, BufRead};

// 读取文件
let mut file = File::open("file.txt")?;
let mut content = String::new();
file.read_to_string(&mut content)?;

// 或者逐行读取
let file = File::open("file.txt")?;
let reader = BufReader::new(file);
for line in reader.lines() {
    println!("{}", line?);
}

// 写入文件
let mut file = File::create("output.txt")?;
file.write_all(b"Hello World\n")?;
file.write_all(b"Second line\n")?;
2 文件定位和二进制操作

Python 二进制操作:


# 二进制读写
with open("file.bin", "rb+") as f:
    f.write(b"0123456789abcdef")
    f.seek(5)  # 移动到第6个字节
    data = f.read(1)  # b'5'
    f.seek(-3, 2)  # 移动到倒数第3个字节
    data = f.read(1)  # b'd'

Rust 二进制操作:


use std::io::{Seek, SeekFrom};

let mut file = File::create("file.bin")?;
file.write_all(b"0123456789abcdef")?;
file.seek(SeekFrom::Start(5))?;  // 移动到第6个字节
let mut buffer = [0; 1];
file.read_exact(&mut buffer)?;   // [53] (ASCII '5')

file.seek(SeekFrom::End(-3))?;   // 移动到倒数第3个字节
file.read_exact(&mut buffer)?;   // [100] (ASCII 'd')
3 JSON 序列化对比

JSON 基本操作

Python json 模块:


import json

# 序列化
data = {"name": "Alice", "age": 30, "scores": [95, 88, 92]}
json_str = json.dumps(data, indent=2)

# 写入文件
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)

# 反序列化
with open("data.json", "r", encoding="utf-8") as f:
    loaded_data = json.load(f)

Rust serde_json 库:


use serde::{Deserialize, Serialize};
use std::fs::File;

#[derive(Serialize, Deserialize, Debug)]
struct Person {
    name: String,
    age: u32,
    scores: Vec<u32>,
}

// 序列化
let data = Person {
    name: "Alice".to_string(),
    age: 30,
    scores: vec![95, 88, 92],
};
let json_str = serde_json::to_string_pretty(&data)?;

// 写入文件
let file = File::create("data.json")?;
serde_json::to_writer_pretty(file, &data)?;

// 反序列化
let file = File::open("data.json")?;
let loaded_data: Person = serde_json::from_reader(file)?;

错误处理对比

Python (异常):


try:
    with open("file.txt", "r") as f:
        content = f.read()
except FileNotFoundError:
    print("文件不存在")
except IOError as e:
    print(f"IO错误: {e}")

Rust (Result 类型):


use std::io;

fn read_file() -> io::Result<String> {
    let mut file = File::open("file.txt")?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    Ok(content)
}

// 使用 match 处理错误
match read_file() {
    Ok(content) => println!("内容: {}", content),
    Err(e) => match e.kind() {
        io::ErrorKind::NotFound => println!("文件不存在"),
        _ => println!("IO错误: {}", e),
    },
}

三、🔑 核心差异总结

特性 Python Rust
错误处理 异常机制 Result/Option 类型
文件操作 with 语句自动关闭 需要显式处理或使用作用域
字符串格式化 f-字符串,灵活 format! 宏,类型安全
序列化 json 模块内置 需要 serde 外部库
编码处理 encoding 参数 需要显式处理 UTF-8
二进制安全 需要指定 ‘b’ 模式 默认就是字节操作

四、💡 实用技巧对比

路径处理

Python pathlib:


from pathlib import Path

path = Path("data") / "file.txt"
if path.exists():
    content = path.read_text(encoding="utf-8")

Rust Path:


use std::path::Path;

let path = Path::new("data").join("file.txt");
if path.exists() {
    let content = std::fs::read_to_string(path)?;
}

临时文件

Python tempfile:


import tempfile

with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    f.write("临时内容")
    temp_name = f.name

Rust tempfile:


use tempfile::NamedTempFile;

let mut temp_file = NamedTempFile::new()?;
writeln!(temp_file, "临时内容")?;
let temp_path = temp_file.path().to_path_buf();

五、🎯 学习建议

1. 从 Python 到 Rust: 准备好面对显式的错误处理和所有权问题

2. 从 Rust 到 Python: 享受异常处理的简洁性,但要注意捕获具体异常

3. 理解哲学差异:
  • Python: “请求宽恕比请求许可容易”

  • Rust: “编译时发现错误比运行时好”

  1. 资源管理: Python 用 with,Rust 用所有权和 Drop trait

两种语言的IO处理都很有特色,Python 更简洁,Rust 更安全!


网站公告

今日签到

点亮在社区的每一天
去签到