如何使用django在我的模板中显示文本文件中的数据

时间:2018-01-11 13:31:14

标签: python django django-templates django-views

我有一个3列用/ t分隔的文本文件我想编写一个索引视图,将第一列显示在组合框中。

这是我的观点

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)

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

这将返回一个包含所有行的第一列的List。

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)

要获得第三列(顺便说一下,使用下一个示例,它更“高效”):

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)

答案 1 :(得分:1)

如果您只想使用第一列

    # 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]
  

如果我想获得第三列,我必须更改

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

您可以将last_column行更改为通用。

    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