Python 在文件中查找字符串
- 
          
            在 Python 中使用文件 readlines()方法查找文件中的字符串
- 
          
            在 Python 中使用文件 read()方法搜索文件中的字符串
- 
          
            在 Python 中使用 find方法搜索文件中的字符串
- 
          
            在 Python 中使用 mmap模块搜索文件中的字符串
 
本教程介绍了如何在 Python 中查找文本文件中的特定字符串。
在 Python 中使用文件 readlines() 方法查找文件中的字符串
    
Pyton 文件 readlines() 方法将文件内容按新行分割成一个列表返回。我们可以使用 for 循环对列表进行遍历,并在每次迭代中使用 in 操作符检查字符串是否在行中。
如果在行中找到了字符串,则返回 True 并中断循环。如果在迭代所有行后没有找到字符串,它最终返回 False。
下面给出了这种方法的示例代码。
file = open("temp.txt", "w")
file.write("blabla is nothing.")
file.close()
def check_string():
    with open("temp.txt") as temp_f:
        datafile = temp_f.readlines()
    for line in datafile:
        if "blabla" in line:
            return True  # The string is found
    return False  # The string does not exist in the file
if check_string():
    print("True")
else:
    print("False")
输出:
True
在 Python 中使用文件 read() 方法搜索文件中的字符串
文件 read() 方法将文件的内容作为一个完整的字符串返回。然后我们可以使用 in 操作符来检查该字符串是否在返回的字符串中。
下面给出一个示例代码。
file = open("temp.txt", "w")
file.write("blabla is nothing.")
file.close()
with open("temp.txt") as f:
    if "blabla" in f.read():
        print("True")
输出:
True
在 Python 中使用 find 方法搜索文件中的字符串
    
一个简单的 find 方法可以与 read() 方法一起使用,以找到文件中的字符串。find 方法被传递给所需的字符串。如果找到了字符串,它返回 0,如果没有找到,则返回 -1。
下面给出一个示例代码。
file = open("temp.txt", "w")
file.write("blabla is nothing.")
file.close()
print(open("temp.txt", "r").read().find("blablAa"))
输出:
-1
在 Python 中使用 mmap 模块搜索文件中的字符串
mmap 模块也可以用来在 Python 中查找文件中的字符串,如果文件大小比较大,可以提高性能。mmap.mmap() 方法在 Python 2 中创建了一个类似字符串的对象,它只检查隐含的文件,不读取整个文件。
下面给出一个 Python 2 中的示例代码。
# python 2
import mmap
file = open("temp.txt", "w")
file.write("blabla is nothing.")
file.close()
with open("temp.txt") as f:
    s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    if s.find("blabla") != -1:
        print("True")
输出:
True
然而,在 Python 3 及以上版本中,mmap 并不像字符串对象一样,而是创建一个 bytearray 对象。所以 find 方法是寻找字节而不是字符串。
下面给出一个示例代码。
import mmap
file = open("temp.txt", "w")
file.write("blabla is nothing.")
file.close()
with open("temp.txt") as f:
    s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    if s.find(b"blabla") != -1:
        print("True")
输出:
True
Syed Moiz is an experienced and versatile technical content creator. He is a computer scientist by profession. Having a sound grip on technical areas of programming languages, he is actively contributing to solving programming problems and training fledglings.
LinkedIn相关文章 - Python String
- 在 Python 中从字符串中删除逗号
- 如何以 Pythonic 的方式检查字符串是否为空
- 在 Python 中将字符串转换为变量名
- Python 如何去掉字符串中的空格/空白符
- 如何在 Python 中从字符串中提取数字
- Python 如何将字符串转换为时间日期 datetime 格式
