How to read and render a .txt file in the Django template?

4

How do I render the data of a arquivo.txt in a Django template?

file content:

1;'one';'foo'

2;'two';'bar'

I return in the template

  

1 - one - foo

     

2 - two - bar

Any tips on where I start?

Following the link

I've tried the following:

def display_text_file():
    with open('output.csv', 'rt') as f:
        r = csv.reader(f, delimiter=';')
        fields = r.next()
        for row in r:
            items = zip(fields, row)
            item = {}
            for (name, value) in items:
                item[name] = value.strip()

Now how do I return this in the context of the view to iterate through the values in the template?

I've tried

{% for line in lines %}
    <p>{{ line.id  }}</p>
{% endfor %}
    
asked by anonymous 25.06.2015 / 21:34

2 answers

4

I'll assume that the ' apostrophes do not exist, so your .txt file should look something like:

1;one;foo
2;two;bar
3;foo;bar

Each line would be equivalent to a database row, this format is very similar to CSV, so I believe you can use link

It should be something like:

import csv

with open('arquivo.txt', 'rb') as csvfile:
     spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
     for row in spamreader:
        print 'ID: %s Nome: %s Extra: ' %(row[0], row[1], row[2])

By the layout, it seems to me that the array is index type (0 ... 99 for example) and not "associative":

{% for line in lines %}
    <p>{{ line.id  }}</p>
{% endfor %}

I believe the data would have to be passed this way:

import csv

item = []

with open('arquivo.txt', 'rb') as csvfile:
     spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
     for row in spamreader:
        tmp = {}
        tmp['id']    = row[0]
        tmp['name']  = row[1]
        tmp['extra'] = row[2]
        item.append(tmp)

I have not worked with python for a while, but I believe it to be. Let me know if there is any exception.

    
25.06.2015 / 21:50
1

It is not complicated, considering that the file is called file.txt , it is in the project root and has this content:

1;one;foo
2;two;bar

Your app with a structure similar to this:

├── admin.py
├── __init__.py
├── migrations
│   └── __init__.py
├── models.py
├── templates
│   └── csv
│       └── csv.html
├── tests.py
└── views.py

And your template with content similar to this:

{% for line in lines%}
    <p>{{ line.id }} - {{ line.nro }} - {{ line.word }}</p>
{% endfor %}

Basically the view needs to have something like this:

import csv
from django.shortcuts import render_to_response


def render_csv(request):
    lines = []
    with open('file.txt', 'r') as f:
        reader = csv.reader(f, delimiter=';')
        for line in reader:
            lines.append(
                {'id': line[0], 'nro': line[1], 'word': line[2]}
            )

    return render_to_response(
        'csv/csv.html',
        {'lines': lines}
    )

Explaining what is being done.

  • First we are reading the txt file (which is actually a csv file) via the csv
  • We will look at this file to build the list of items that will later be used in the context of the response.
  • Lastly, we use the django shortcut render_to_response that receives the template path and context as the parameter.
  • The html response looks something like:

    <p>1 - one - foo</p>
    <p>2 - two - bar</p>
    

    I hope you have helped.

        
    27.06.2015 / 14:57