youssef hassoun
youssef hassoun

Reputation: 350

how to display data from a text file in my templates using django

I have a text file with 3 columns separated by /t I want to write an index view who display the first column into a combobox.

This is my view

def index(request):
//opening my file 
myfile  = open("myfile.txt", "r")


//read file and get the first column, i dont know how 
myfile.read()

context = { first_column : first_column}

return render(request,myapp/mytemplate.html,context)

Thanks for help!

Upvotes: 1

Views: 2643

Answers (2)

Abdullah
Abdullah

Reputation: 129

This return a List with the first columns of all the rows.

def index(request):
    with open('myfile.txt','r') as file:
        #list to return
        to_return = []

        a = file.readlines()
        aux = ''
        for tab in a:
            for subtab in tab:
                #remove .replace if you want to add the tab
                aux += subtab.replace('\t', '')
                if subtab == '\t': #here you detect a tab
                    # print("Subtab")
                    to_return.append(aux)
                    aux = ''
                    break

        context = { first_column : to_return}
        return render(request,myapp/mytemplate.html,context)

To get the third columns (btw use the next example, it is more "efficient"):

def index(request):
    with open('txt.txt','r') as file:
        #list to return
        to_return = []
        a = file.readlines()

        for tab in a:
            tab = tab.split() #this "divides" the columns 
            #then just append the third column
            to_return.append(tab[2])

        context = { first_column : to_return}
        return render(request,myapp/mytemplate.html,context)

Upvotes: 1

Eagllus
Eagllus

Reputation: 447

If you want only the first column you could use

    # Read the full file
    myfile = open("myfile.txt", "r").read()

    # Split file by new lines
    # Will make an array looking like
    # ['first_1/tsecond/tlast', 'first_2/tsecond_2/tlast_2']
    lines = myfile.split('\n')

    # This splits 'lines' by /t and returns only the first one
    # making a new array with only the first column.
    # ['first_1', 'first_2']
    first_column = [line.split('/t')[0] for line in lines]

if i want to get the third column, where i have to change

    # Add this below the last line
    last_column = [line.split('/t')[2] for line in lines]

You can change the last_column line to something generic.

    lines = [line.split('/t') for line in lines]
    print(lines) : [['first_1', 'second', 'last'], ['first_2', 'second_2', 'last_2']]
    print(lines[0]) : ['first_1', 'second', 'last']
    print(lines[1]) : ['first_2', 'second_2', 'last_2']
    print(lines[0][0]) : first
    print(lines[1][1]) : second_2

Upvotes: 1

Related Questions