python查找包含字符串的行
时间: 2023-12-23 14:04:03 浏览: 20
你可以使用 Python 的文件操作和字符串操作来实现这个功能。具体的方法如下:
1. 打开文件,使用 `open()` 函数来打开文件,并使用 `readlines()` 函数读取所有行。
```python
with open('filename.txt', 'r') as file:
lines = file.readlines()
```
2. 查找包含特定字符串的行,遍历所有行,使用 `find()` 函数来查找包含特定字符串的行,并将它们添加到一个列表中。
```python
search_string = 'example'
result = []
for line in lines:
if line.find(search_string) != -1:
result.append(line)
```
3. 打印结果,使用 `print()` 函数将结果打印出来。
```python
for line in result:
print(line)
```
完整代码如下:
```python
with open('filename.txt', 'r') as file:
lines = file.readlines()
search_string = 'example'
result = []
for line in lines:
if line.find(search_string) != -1:
result.append(line)
for line in result:
print(line)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)