Python文件读写核心是使用open()函数打开文件,通过read()、write()等方法操作内容,并用with语句确保文件安全关闭。

Python中文件读写,核心在于使用内置的
open()
read()
write()
readline()
with
在Python里处理文件,说白了就是和操作系统打交道,告诉它:“嘿,我想对这个文件做点什么。” 这其中涉及到几个关键点:打开文件、操作文件内容、最后关闭文件。我个人经验是,理解这三步,文件操作基本就稳了。
1. 打开文件:open()
这是所有文件操作的起点。
open()
立即学习“Python免费学习笔记(深入)”;
# 示例:打开一个文件
file_object = open('my_document.txt', 'r', encoding='utf-8')这里,
'my_document.txt'
'r'
encoding='utf-8'
常见的打开模式有:
'r'
'w'
'a'
'x'
FileExistsError
'b'
'r'
'w'
'a'
'rb'
'wb'
'+'
'r'
'w'
'a'
'r+'
'w+'
'a+'
2. 操作文件内容
一旦文件被打开,你就可以通过返回的文件对象进行读写操作了。
读取文件:
read(size=-1)
size
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print("所有内容:", content)这里我直接用了
with
readline(size=-1)
with open('example.txt', 'r', encoding='utf-8') as f:
first_line = f.readline()
print("第一行:", first_line.strip()) # strip() 去掉末尾的换行符readlines()
with open('example.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print("所有行列表:", lines)迭代文件对象: 这是处理大文件时我最推荐的方式,因为它一行一行地读取,不会一次性加载所有内容到内存,非常高效。
with open('example.txt', 'r', encoding='utf-8') as f:
for line in f:
print("逐行读取:", line.strip())写入文件:
write(string)
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("这是第一行内容。
")
f.write("这是第二行内容。
")writelines(list_of_strings)
lines_to_write = ["苹果
", "香蕉
", "橙子
"]
with open('fruits.txt', 'w', encoding='utf-8') as f:
f.writelines(lines_to_write)3. 关闭文件:close()
with
文件操作完成后,必须调用
file_object.close()
然而,更优雅、更安全的方式是使用
with
with open('my_file.txt', 'r', encoding='utf-8') as f:
# 在这里进行文件操作
content = f.read()
print(content)
# 文件在with代码块结束后会自动关闭,即使发生异常with
try...finally
with
我敢说,任何一个稍微深入一点的Python开发者,都或多或少被编码问题“坑”过。这玩意儿就像个隐形的地雷,平时没事,一遇到特定场景(比如跨平台、处理老旧数据),“砰”的一声就炸了。所以,理解并解决编码问题,绝对是文件读写中的一个关键技能点。
编码问题的根源:
如何避免和解决:
始终明确指定编码: 这是最重要的原则,没有之一。在
open()
encoding
# 写入文件时,明确指定UTF-8
with open('output_utf8.txt', 'w', encoding='utf-8') as f:
f.write("你好,世界!")
# 读取文件时,也明确指定UTF-8
with open('output_utf8.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)对于大多数现代应用,
utf-8
处理未知编码或错误字符:errors
open()
errors
# 假设文件可能包含无法用UTF-8解码的字符
try:
with open('mystery_file.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
except UnicodeDecodeError:
print("尝试UTF-8解码失败,尝试其他编码或忽略错误。")
# 尝试忽略错误字符
with open('mystery_file.txt', 'r', encoding='utf-8', errors='ignore') as f:
content_ignored = f.read()
print("忽略错误后内容:", content_ignored)
# 或者替换错误字符
with open('mystery_file.txt', 'r', encoding='utf-8', errors='replace') as f:
content_replaced = f.read()
print("替换错误后内容:", content_replaced)
# 甚至可以尝试其他可能的编码,比如GBK
try:
with open('mystery_file.txt', 'r', encoding='gbk') as f:
content_gbk = f.read()
print("尝试GBK解码后内容:", content_gbk)
except UnicodeDecodeError:
print("GBK解码也失败了...")errors
'strict'
UnicodeDecodeError
'ignore'
'replace'
U+FFFD
'backslashreplace'
统一编码标准: 如果你的项目涉及到多个文件或多个系统,最好内部约定一个统一的编码标准(强烈推荐UTF-8),并确保所有文件操作都遵循这个标准。这能从根本上减少编码问题的发生。
处理大文件,比如几个GB甚至几十GB的日志文件、数据集,如果还像读小文件那样一股脑儿
read()
readlines()
1. 逐行迭代(最常用且高效):
这是我处理文本大文件时的首选方法。Python的文件对象本身就是迭代器,这意味着你可以直接在
for
def process_large_text_file_line_by_line(filepath):
line_count = 0
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
# 在这里处理每一行数据
# 比如,解析CSV行、筛选特定内容等
if "error" in line.lower():
print(f"发现错误日志:{line.strip()}")
line_count += 1
# 为了演示,我们只处理前100行
if line_count > 10000: # 假设文件很大,我们只看前10000行
break
print(f"总共处理了 {line_count} 行。")
# 假设有一个名为 'large_log.txt' 的大文件
# process_large_text_file_line_by_line('large_log.txt')这种方法内存占用极低,非常适合处理日志文件、大型文本数据集等。
2. 分块读取(read(size)
当文件不是纯文本,或者你需要按固定大小的块来处理数据时(例如,处理二进制文件、自定义协议的数据包),
read(size)
def process_large_binary_file_in_chunks(filepath, chunk_size=4096): # 默认4KB一块
total_bytes_processed = 0
with open(filepath, 'rb') as f: # 注意是二进制模式 'rb'
while True:
chunk = f.read(chunk_size)
if not chunk: # 读取到文件末尾
break
# 在这里处理读取到的数据块
# 比如,计算哈希值、查找特定字节序列、传输数据等
# print(f"读取到 {len(chunk)} 字节的数据块。")
total_bytes_processed += len(chunk)
# 假设我们只处理前1MB
if total_bytes_processed > 1024 * 1024:
print("已处理超过1MB数据,停止。")
break
print(f"总共处理了 {total_bytes_processed} 字节。")
# 假设有一个名为 'large_image.bin' 的大二进制文件
# process_large_binary_file_in_chunks('large_image.bin')这种方式同样可以有效控制内存使用,因为它每次只加载一小部分数据。
3. 内存映射文件(mmap
对于某些高级场景,特别是你需要对大文件进行随机访问或者需要像操作内存一样操作文件时,Python的
mmap
import mmap
import os
def search_in_large_file_with_mmap(filepath, search_term_bytes):
if not os.path.exists(filepath):
print(f"文件不存在: {filepath}")
return False
with open(filepath, 'r+b') as f: # 注意 'r+b' 模式
# 使用mmap创建内存映射
# mmap.ACCESS_READ 表示只读访问
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
# 现在可以像操作字节串一样操作mm对象
# 比如,查找一个字节序列
index = mm.find(search_term_bytes)
if index != -1:
print(f"找到 '{search_term_bytes.decode()}' 在文件中的偏移量: {index}")
# 还可以读取特定位置的数据
# print(mm[index:index + len(search_term_bytes) + 20].decode())
return True
else:
print(f"未找到 '{search_term_bytes.decode()}'")
return False
# 创建一个示例大文件(如果不存在)
# with open('test_mmap_large_file.txt', 'w', encoding='utf-8') as f:
# for i in range(100000):
# f.write(f"Line {i}: This is some content for line {i}.
")
# f.write("Here is the secret phrase I am looking for.
")
# for i in range(100000, 200000):
# f.write(f"Line {i}: More content.
")
# search_in_large_file_with_mmap('test_mmap_large_file.txt', b'secret phrase')mmap
文件路径,这个看似简单的小东西,在不同操作系统上却能带来不少麻烦。Windows习惯用反斜杠
/
'C:UsersDocumentsile.txt'
os.path
pathlib
pathlib
os.path
1. 使用 os.path
os.path
*`os.path.join(paths)`:** 这是最常用的函数,用于将多个路径组件智能地连接起来。它会自动使用正确的路径分隔符。
import os
# 硬编码路径分隔符的错误示范
# windows_path = 'C:\Users\user\Documents\report.txt'
# linux_path = '/home/user/documents/report.txt'
# 使用 os.path.join
base_dir = 'my_project'
sub_dir = 'data'
file_name = 'config.json'
full_path = os.path.join(base_dir, sub_dir, file_name)
print(f"拼接后的路径: {full_path}")
# 在Windows上可能输出: my_projectdataconfig.json
# 在Linux上可能输出: my_project/data/config.json无论在哪个系统上运行,
os.path.join()
os.path.abspath(path)
relative_path = 'temp/my_file.txt'
abs_path = os.path.abspath(relative_path)
print(f"绝对路径: {abs_path}")os.path.dirname(path)
path_with_file = '/home/user/documents/report.txt'
directory = os.path.dirname(path_with_file)
print(f"目录部分: {directory}") # 输出: /home/user/documentsos.path.basename(path)
path_with_file = '/home/user/documents/report.txt'
filename = os.path.basename(path_with_file)
print(f"文件名部分: {filename}") # 输出: report.txt2. 使用 pathlib
pathlib
pathlib
os.path
创建 Path
from pathlib import Path
# 创建一个Path对象
p = Path('my_project') / 'data' / 'config.json'
print(f"Path对象: {p}")
# Path对象会自动处理路径分隔符这里最酷的是,你可以直接使用
/
os.path.join()
路径属性和方法:
Path
from pathlib import Path
p = Path('/home/user/documents/report.txt')
print(f"文件名: {p.name以上就是Python中文件怎么读写 Python中文件读写操作指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号