ToolkitX
知识库工具箱

文件操作

文件读写、with语句、路径处理

15min·入门

01. 文件读写基础

Python 使用 open() 函数打开文件。推荐使用 with 语句自动管理文件资源。常用打开模式:r 只读,w 写入(覆盖),a 追加。
python
# 写入文件
with open("hello.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("第二行内容\n")

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

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

02. JSON 与 CSV 操作

Python 的 json 模块可以方便地读写 JSON 文件。csv 模块用于处理 CSV 格式数据。
python
import json
import csv

# 写入 JSON
data = {"name": "张三", "age": 25, "scores": [90, 85, 92]}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)

# 读取 JSON
with open("data.json", "r", encoding="utf-8") as f:
loaded = json.load(f)

# 读取 CSV
with open("students.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
      print(f"{row['姓名']} 成绩: {row['成绩']}")

知识测验

1/5正确 0

with 语句在文件操作中的作用是什么?

下一节

异常处理

下一节