Python 在文件中查找字符串
本教程介绍了如何在 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
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串