来源:
"""
http://tv3.zfpaper.net
http://tv2.zfpaper.net
http://tv1.zfpaper.net
http://www.zfpaper.net
http://zfpaper.net
"""Python内置的open()函数是处理文件的基础。该函数返回一个文件对象,可用于读取或写入文件。
file_object = open('filename.txt', 'r')参数说明:
'filename.txt' - 要打开的文件路径'r' - 打开模式(读取模式)# 打开文件
file = open('example.txt', 'r')
# 读取文件内容
content = file.read()
# 打印内容
print(content)
# 关闭文件
file.close()重要提示:使用open()后必须调用close()关闭文件,否则可能导致资源泄漏。
Python的with语句提供了更优雅的文件处理方式,它能自动管理文件资源,确保文件正确关闭。
# 使用with语句打开文件
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 文件会在with块结束后自动关闭
# 无需手动调用close()优势:代码更简洁,避免忘记关闭文件,异常处理更安全。
read()方法一次性读取文件的全部内容,返回一个字符串。
with open('example.txt', 'r') as file:
# 读取整个文件内容
content = file.read()
print("文件内容:")
print(content)
# 可以指定读取的字符数
file.seek(0) # 将文件指针移回开头
first_50 = file.read(50)
print("\n前50个字符:")
print(first_50)seek(0)将指针重置到文件开头readline()方法每次读取文件的一行内容,适合处理大文件或需要逐行处理的场景。
with open('example.txt', 'r') as file:
# 读取第一行
line1 = file.readline()
print("第一行:", line1)
# 读取第二行
line2 = file.readline()
print("第二行:", line2)
# 循环读取剩余所有行
print("\n剩余内容:")
while True:
line = file.readline()
if not line:
break
print(line, end='')readlines()方法读取文件的所有行,返回一个字符串列表,每个元素代表文件的一行。
with open('example.txt', 'r') as file:
# 读取所有行
lines = file.readlines()
print(f"文件共有 {len(lines)} 行")
print("\n文件内容:")
# 打印每行内容(带行号)
for i, line in enumerate(lines, 1):
print(f"{i}: {line.strip()}")lines = [line.strip() for line in file.readlines()]正确处理文件路径是文件操作的重要环节,Python提供了多种处理路径的方式。
import os
# 获取当前工作目录
current_dir = os.getcwd()
print("当前目录:", current_dir)
# 组合路径
file_path = os.path.join(current_dir, 'data', 'example.txt')
print("完整路径:", file_path)
# 检查文件是否存在
if os.path.exists(file_path):
print("文件存在")
else:
print("文件不存在")from pathlib import Path
# 创建Path对象
file_path = Path('data') / 'example.txt'
# 检查文件
if file_path.exists():
print(f"文件大小: {file_path.stat().st_size} 字节")
# 读取文件内容
content = file_path.read_text(encoding='utf-8')
print(content[:100]) # 打印前100个字符文件操作可能遇到各种错误,如文件不存在、权限问题等,使用异常处理可以增强程序健壮性。
try:
with open('nonexistent.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("错误:文件不存在!")
except PermissionError:
print("错误:没有文件访问权限!")
except Exception as e:
print(f"发生未知错误: {str(e)}")
else:
print("文件读取成功!")
finally:
print("文件操作完成")try:
# 尝试使用UTF-8编码打开
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
except UnicodeDecodeError:
try:
# 如果UTF-8失败,尝试其他编码
with open('example.txt', 'r', encoding='latin-1') as file:
content = file.read()
except Exception as e:
print(f"解码失败: {str(e)}")encoding='utf-8'read()或readlines()readline()或直接迭代文件对象)os.path或pathlib确保跨平台兼容性原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。