当前位置: 首页 > ops >正文

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

一、输出格式化对比

字符串格式化方法对比

格式化方式PythonRust
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),},
}

三、🔑 核心差异总结

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

四、💡 实用技巧对比

路径处理

Python pathlib:


from pathlib import Pathpath = 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 tempfilewith 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 更安全!

http://www.xdnf.cn/news/19656.html

相关文章:

  • Linux系统shell脚本(二)
  • 【Python - 基础 - 工具】解决pycharm“No Python interpreter configured for the project”问题
  • 机器学习入门,支持向量机
  • Vite + React + Tailwind v4 正确配置指南(避免掉进 v3 的老坑)
  • 为什么程序员总是发现不了自己的Bug?
  • Flutter 3.35.2 主题颜色设置指南
  • 使用 qmake 生成 Makefile,Makefile 转换为 Qt 的 .pro 文件
  • Redis核心数据类型解析——string篇
  • 基于YOLO8的番茄成熟度检测系统(数据集+源码+文章)
  • 2025年女性最实用的IT行业证书推荐:赋能职业发展的8大选择
  • Elasticsearch面试精讲 Day 5:倒排索引原理与实现
  • IoTDB对比传统数据库的五大核心优势
  • 深度估计:单目视觉实现车距测量和车速估计(含完整项目代码)
  • ubantu20.04 git clone 无法连接问题与解决方法
  • netstat用法
  • 别再让分散 IO 拖慢性能!struct iovec:高效处理聚集 IO 的底层利器
  • pikachu之 unsafe upfileupload (不安全的文件上传漏洞)
  • 力扣hot100:除自身以外数组的乘积(除法思路和左右前缀乘积)(238)
  • 毕业项目推荐:70-基于yolov8/yolov5/yolo11的苹果成熟度检测识别系统(Python+卷积神经网络)
  • 【无人机三维路径规划】基于遗传算法GA结合粒子群算法PSO无人机复杂环境避障三维路径规划(含GA和PSO对比)研究
  • 基于单片机醉酒驾驶检测系统/酒精检测/防疲劳驾驶设计
  • 基于单片机雏鸡孵化恒温系统/孵化环境检测系统设计
  • WPF启动窗体的三种方式
  • 【Day 42】Shell-expect和sed
  • 【python】lambda函数
  • Ubuntu 24.04 服务器配置MySQL 8.0.42 三节点集群(一主两从架构)安装部署配置教程
  • ubuntu部署MySQL服务
  • 数据结构——树(04二叉树,二叉搜索树专项,代码练习)
  • 【硬核干货】把 DolphinScheduler 搬进 K8s:奇虎 360 商业化 900 天踩坑全记录
  • 从零开始:用代码解析区块链的核心工作原理