温馨提示×

怎么用python在文本文件批量查找

小亿
120
2023-09-13 15:08:27
栏目: 编程语言

可以使用Python的文件操作和字符串操作来实现在文本文件中批量查找的功能。下面是一个简单的示例代码:

def search_in_files(keyword, file_path):
with open(file_path, 'r') as file:
for line_number, line in enumerate(file, start=1):
if keyword in line:
print(f"在第{line_number}行找到了'{keyword}'")
def batch_search(keyword, folder_path):
import os
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
search_in_files(keyword, file_path)
# 调用示例
folder_path = '文件夹路径'  # 替换为实际的文件夹路径
keyword = '关键字'  # 替换为实际的关键字
batch_search(keyword, folder_path)

在上述代码中,search_in_files函数用于在单个文件中查找关键字,并输出找到的行号和关键字信息。batch_search函数用于批量遍历指定文件夹中的文本文件,并调用search_in_files函数来查找关键字。

你需要将代码中的文件夹路径关键字替换为你实际的文件夹路径和关键字,然后运行代码即可实现批量查找功能。

0