如何读取带指定关键则的文件?
时间: 2024-01-04 08:04:07 浏览: 114
要读取带指定关键字的文件,你可以按照以下步骤操作:
1. 打开文件并读取所有行,将其存储在一个列表中。
2. 遍历列表中的每一行,如果行包含指定的关键字,则将该行添加到另一个列表中。
3. 返回包含指定关键字的所有行的列表。
下面是一个Python的示例代码,供你参考:
```python
def read_file_with_keyword(filename, keyword):
with open(filename, "r") as file:
all_lines = file.readlines()
matched_lines = []
for line in all_lines:
if keyword in line:
matched_lines.append(line)
return matched_lines
```
你可以调用这个函数来读取包含指定关键字的文件,例如:
```python
matched_lines = read_file_with_keyword("example.txt", "apple")
print(matched_lines)
```
这将打印出所有包含关键字“apple”的行。
阅读全文
相关推荐


















