在Python中使用内置open()
一、基础文件打开方法
- plaintext复制函数基础用法
open()
通过plaintext复制直接打开文本文件,文件对象 = open("文件路径", "r")
plaintext复制表示读取模式。例如:"r"
python复制file = open("data.txt", "r") content = file.read() file.close() # 必须手动关闭 ``` ``` 需注意**手动关闭文件**,否则可能导致资源泄漏。
- 自动资源管理:plaintext复制语句
with
使用plaintext复制可自动关闭文件,避免遗漏with open(...) as file
plaintext复制:close()
python复制with open("data.txt", "r") as file: content = file.read() # 代码块结束后自动关闭
二、应对不同文件场景
-
读取模式选择
- 文本模式(plaintext复制):默认处理字符串,适合.txt、.csv等文本文件。
'r'
- 二进制模式(plaintext复制):读取图片、视频等非文本文件,保留原始字节数据。
'rb'
- 追加模式(plaintext复制):允许同时读写文件,指针初始位置在开头。
'r+'
- 文本模式(
-
处理编码问题
若文件含中文等特殊字符,需指定plaintext复制参数(如encoding
plaintext复制):encoding='utf-8'
python复制with open("data.txt", "r", encoding="utf-8") as file: print(file.read())
三、异常处理与兼容性
-
捕获文件不存在错误
使用plaintext复制块处理try-except
plaintext复制,增强代码健壮性:FileNotFoundError
python复制try: with open("data.txt", "r") as file: print(file.read()) except FileNotFoundError: print("文件路径错误或文件不存在!")
-
跨平台路径兼容
使用plaintext复制模块处理不同操作系统的路径分隔符:os.path
python复制import os file_path = os.path.join("documents", "data.txt")
四、进阶文件读取技巧
-
逐行读取大文件
用plaintext复制逐行加载,避免内存溢出:for line in file
python复制with open("large_data.log", "r") as file: for line in file: process(line) # 逐行处理
-
读取结构化数据
- CSV文件:使用plaintext复制解析表格数据。
csv.reader
- JSON文件:用plaintext复制直接转换为字典或列表。
json.load()
- CSV文件:使用
总结:打开文件时优先选择
with
csv
json