Python 在文件中查找字符串

您所在的位置:网站首页 查找文档怎么查找内容 Python 在文件中查找字符串

Python 在文件中查找字符串

2024-07-09 12:49| 来源: 网络整理| 查看: 265

在 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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3