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

Asked

Viewed 1,225 times

4

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

contents of the archive:

1;'one';'foo'

2;'two';'bar'

I return in the template

1 - one - foo

2 - two - bar

Any hint where I start?

Following the website http://www.coderholic.com/parsing-csv-data-in-python/

I 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 view context to iterate for the values in the template?

I tried to

{% for line in lines %}
    <p>{{ line.id  }}</p>
{% endfor %}
  • It’s actually a TXT anyway.

  • Are you sure you want to keep the dice in CSV, instead of pushing to a SGBD?

  • Yes, I need to test site before I go up to production.

  • ...the implication is that you do not have a test database for local development?

  • The intention of this line and the following is to build a dictionary using the first line of the CSV as the "header" of the "spreadsheet".

  • that’s right.....

Show 1 more comment

2 answers

4


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

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

Each line would be equivalent to a database line, this format is very similar to CSV, so I believe you can use https://docs.python.org/2/library/csv.html

It must 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])

From the layout, it seems that the array is of type index (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 haven’t worked with python for some time, but I believe this is it. Let me know if there are any Exception.

  • I forgot to mention that it is not rendering in the Django template, I tried to play in the context, but I do not know what to put there, whether spamreader or something else.

  • I don’t know how you are using the layout, I didn’t see any code in your question @Regisdasilva, please provide a minimal example of the template and how you are trying to add the data

  • I edited the question.

  • @Regisdasilva see if it helps you after this issue

  • Thanks @Guilherme Nascimento.

  • Why instead of "supposing that the characters ' do not exist" and create a reader with the quotechar | you do not create a Reader with quotechar ' and meets the user problem?

  • I think I understand what you meant to say @jsbueno the point is that when I said "' there are no" we still had no idea if the data structure (this referred to the posting before the http://answall.com/revisions/71231/1) that the author would use was actually equivalent to CSV and was trying to suggest a simpler example. However, it seems to me that the author did not really have a defined file "format", it seems to me that the answer answered his doubt. I will edit as soon as possible - I am on mobile :). Thank you.

Show 2 more comments

1

It’s not complicated, considering the file’s called file.txt, is at the root of the project 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’s being done.

  1. First we’re reading the file txt (which is actually a file csv) through the package csv (built-in python)
  2. We will continue in this file to assemble the list of items that will later be used in context of Sponse.
  3. Finally we use the shortcut render_to_response from Django that takes the template path and context as parameter.

The html answer looks something like:

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

I hope it helped.

  • Your answer helped yes, but I already had validity the previous answer before, but it was worth, for future versions your solution tb serves.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.