用python 遍历文件目录下的txt文件,搜索文件内容,如果含有关键字"123 @",则提取此行内容和该文件的路径,写入到名为456的新文件中
时间: 2024-04-14 15:28:56 浏览: 58
好的,你可以使用以下代码来实现:
```python
import os
def search_files(directory, keyword):
result = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, 'r') as f:
lines = f.readlines()
for line in lines:
if keyword in line:
result.append((line.strip(), file_path))
return result
def write_to_file(result, output_file):
with open(output_file, 'w') as f:
for line, file_path in result:
f.write(f"{line}\t{file_path}\n")
directory = '/path/to/directory' # 替换为你的目录路径
keyword = '123 @'
output_file = '456.txt'
result = search_files(directory, keyword)
write_to_file(result, output_file)
```
请将`/path/to/directory`替换为实际的文件目录路径。执行以上代码后,将会在当前目录下生成一个名为`456.txt`的文件,其中包含含有关键字`"123 @"`的文本行及其对应的文件路径。
阅读全文