文件操作

打开文件的模式

模式 含义
'r' 只读(默认)
'w' 只写(覆盖)
'a' 追加
'x' 排他创建(文件存在则报错)
'b' 二进制模式
't' 文本模式(默认)
'+' 读写

读文件

# 读取全部
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()              # 读取全部
    # line = f.readline()           # 读一行
    # lines = f.readlines()         # 读取全部行 → 列表

# 逐行读取(大文件推荐)
with open("file.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

写文件

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!\n")
    f.writelines(["第一行\n", "第二行\n"])

⚠️ 始终使用 with 语句!

with 语句会自动关闭文件,即使发生异常也不会泄漏资源。

# 不使用 with 的旧写法(不推荐)
f = open("file.txt", "r")
try:
    content = f.read()
finally:
    f.close()

文件路径操作

import os

# 路径拼接(跨平台)
path = os.path.join("folder", "subfolder", "file.txt")
# Windows: folder\subfolder\file.txt
# macOS/Linux: folder/subfolder/file.txt

# 路径信息
os.path.exists(path)           # 路径是否存在
os.path.isfile(path)           # 是否是文件
os.path.isdir(path)            # 是否是目录
os.path.basename(path)         # "file.txt"
os.path.dirname(path)          # "folder/subfolder"
os.path.splitext("a.txt")      # ("a", ".txt")

# 目录操作
os.makedirs("a/b/c", exist_ok=True)  # 递归创建目录
os.listdir(".")                       # 列出目录内容

上一篇:[[Python-类与面向对象]] | 下一篇:[[Python-异常处理]]

更多推荐