python 查找文件中的字符串所在行
时间: 2023-05-04 11:04:19 浏览: 420
Python 是一门特别适合文本处理的编程语言,我们可以很方便的使用 Python 查找文件中的字符串所在行。
下面是一个简单的 Python 代码示例:
```python
# 打开文件并读取所有行
with open('example.txt') as file:
lines = file.readlines()
# 遍历每一行,查找包含目标字符串的行
target_string = 'hello'
result = []
for i, line in enumerate(lines):
if target_string in line:
result.append(i)
# 打印结果
print('目标字符串“{}”出现在以下行:'.format(target_string))
for r in result:
print(r)
```
上述代码首先打开一个名为 `'example.txt'` 的文件并将其所有行读取到一个列表中。然后遍历每一行,在包含目标字符串的行号 `i` 和行内容 `line` 上进行判断。我们将包含目标字符串的行号存储在一个列表中,最后打印这个列表即可。
需要注意的是,这种方法查找字符串所在行的时候是区分大小写的,如果需要忽略大小写,可以在判断时使用 `if target_string.lower() in line.lower():` 条件替换。
相关问题
python 在txt中查找字符串所在行
Python可以通过打开并逐行读取.txt文件来查找字符串所在行。具体步骤如下:
1. 首先,使用Python的open函数打开.txt文件,并指定打开模式为只读("r")。
```python
file = open("file.txt", "r")
```
2. 接着,使用for循环逐行读取文件内容,将每一行存储到变量line中。
```python
for line in file:
```
3. 在循环中,使用字符串的find方法对每一行进行查找。如果字符串被找到,find方法会返回该字符串在行中的索引位置。
```python
if line.find("查询字符串") != -1:
```
4. 如果字符串被找到,可以打印或处理所在行的内容。
```python
print(line)
```
5. 最后,关闭文件。
```python
file.close()
```
通过上述步骤,可以在.txt文件中查找指定的字符串,并找出包含该字符串的行。请注意,这个方法仅能找到完全匹配的字符串,如果要实现模糊匹配或其他高级查找功能,可以使用正则表达式或其他相关方法进行扩展。
python 字符串所在行的搜索
可以使用 python 的 re 模块来实现在文件中搜索字符串所在行的功能。例如:
```python
import re
def search_string(filepath,string):
with open(filepath,'r') as f:
lines = f.readlines()
for i,line in enumerate(lines):
if re.search(string,line):
print(f'{i+1}:{line}')
search_string('test.txt','search_string')
```
这段代码打开名为'test.txt' 的文件,并在其中搜索 "search_string" 字符串,找到匹配的行并打印出来。
相关推荐
![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)
![](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)
![](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)