open()
函数和 read()
方法的重构使用open()
函数是Python中用于打开文件的内置函数,它返回一个文件对象。read()
方法则是文件对象的一个方法,用于读取文件的内容。
.txt
, .csv
。with
语句可以自动管理文件的打开和关闭,避免资源泄露。以下是重构后的 open()
和 read()
方法的使用示例:
def read_file(file_path, mode='r'):
"""
读取文件内容的函数,支持文本和二进制模式。
:param file_path: 文件路径
:param mode: 文件打开模式,默认为文本读取模式 'r'
:return: 文件内容或字节流
"""
try:
with open(file_path, mode) as file:
content = file.read()
return content
except FileNotFoundError:
print(f"文件 {file_path} 未找到。")
except PermissionError:
print(f"没有权限读取文件 {file_path}。")
except IOError as e:
print(f"读取文件 {file_path} 时发生错误: {e}")
# 使用示例
text_content = read_file('example.txt')
binary_content = read_file('example.jpg', 'rb')
print("文本内容:", text_content)
print("二进制内容:", binary_content)
问题1:文件未找到
问题2:权限错误
问题3:IO错误
通过上述方法,可以有效地重构 open()
和 read()
的使用,提高代码的健壮性和可维护性。
领取专属 10元无门槛券
手把手带您无忧上云