I have multiple text files in a folder, which all of them created dynamically from Cisco Switches. I want to read each file and display on the web. So I have this code:
def idf(request):
context = {}
all_files = os.listdir("devices/")
for i in all_files:
with open(i, 'r') as readFile:
switch_ports = readFile.readlines()
print(switch_ports)
readFile.close()
context.update({'switch_ports': switch_ports})
return render(request, 'idf.html', context)
The problem is, it loops through the function, and only renders the last file. So it is basically replacing the content. How can I keep all of them? So they just keep appending to the last file?
Here is the template:
{% block everyDevice %}
{% block switch_ports %}
<h1>{{ everyDevice }}</h1>
{% for result in switch_ports %}
<p>{{ result }}</p>
{% endfor %}
{% endblock %}
{% endblock %}
</main>
CodePudding user response:
You override the key in your context on every iteration of the loop, store the data in a list (or whatever is appropriate) and pass that list to your context after the loop
def idf(request):
switch_ports = []
all_files = os.listdir("devices/")
for i in all_files:
with open(i, 'r') as readFile:
switch_ports.append(readFile.read())
return render(request, 'idf.html', {'switch_ports': switch_ports})
Use a pre
tag to output the results as this will format the text with a monospace font and most likely look how you want. Also use read()
instead of readlines()
to get the raw txt instead of a list of lines
{% for result in switch_ports %}
<pre>{{ result }}</pre>
{% endfor %}
CodePudding user response:
context.update({"switch_ports": switch_ports})
is going to replace the existing "switch_ports" with whatever the latest iteration value is at that time so your issue makes perfect sense.
My recommendation would be to use a list append and then join to achieve the desired result.
def idf(request):
context = {}
switch_ports = []
all_files = os.listdir("devices/")
for i in all_files:
with open(i, 'r') as readFile:
switch_port = readFile.readlines()
print(switch_port)
switch_ports.append(switch_port)
readFile.close()
context.update({'switch_ports': "".join(switch_ports)})
return render(request, 'idf.html', context)
If you would like your file contents to be joined/separated by something other than "", you can use a different separator as outlined in the join documentation.