我试图在本地PC日志文件上运行搜索。如果我从本地pc的CLI运行它,下面的函数工作正常。基本上该函数会搜索目录中的所有文件。如果其中一个文件中的一行有单词" bee"在其中,那条线将被打印出来。
我想要做的是运行脚本并打印出每一行都有" bee"到index.html文件页面。我想以下会起作用,但我想我错过了一些东西。建议很受欢迎。
urlpatterns = [
url(r'^$', views.index, name='index'),
]
import re
import os
def index(request):
log_location = "C:\\folder1"
for dirpath, dirnames, log_file in os.walk(log_location):
for file in log_file:
file = os.path.join(dirpath, file)
with open(file) as open_directory:
for line in open_directory:
if 'bee' in line:
context = line
print(line)
return render(request, 'testapp/index.html', context)
<html></html>
<h1>{{line}}</h1>
</html>
答案 0 :(得分:0)
看起来你需要建立一个列表。
def index(request):
log_location = "C:\\folder1"
lines = []
for dirpath, dirnames, log_file in os.walk(log_location):
for file in log_file:
file = os.path.join(dirpath, file)
with open(file) as open_directory:
for line in open_directory:
if 'bee' in line:
lines.append(line)
您需要将字典传递给渲染器
rendered_data = {'line': r'\n'.join(lines) }
return render(request, 'testapp/index.html', rendered_data )