以下是一个示例解决方案,其中演示了如何按模式读取文件:
def read_file_by_pattern(file_path, pattern):
try:
with open(file_path, 'r') as file:
for line in file:
if pattern in line:
print(line.strip()) # 或者根据需要对匹配的行进行处理
except FileNotFoundError:
print(f"文件 '{file_path}' 不存在。")
# 示例用法
read_file_by_pattern("example.txt", "pattern")
在上述示例中,read_file_by_pattern
函数接受文件路径和模式作为参数。它使用 open
函数打开文件,并使用 with
语句确保文件在使用后正确关闭。然后,它遍历文件的每一行,如果模式出现在行中,则打印该行(或根据需要进行处理)。
请注意,上述示例仅适用于读取文本文件。如果要读取二进制文件,可以将打开文件的模式从 'r'
更改为 'rb'
,并使用适当的方法处理二进制数据。
上一篇:按模式对字符向量进行子集划分
下一篇:按模式反连接