jas jas - 5 months ago 13
Python Question

How to read a file correctly in flask

I would like to pass a list to Jinja that it can iterate over and populate the values of select field. I'm struggling to build the list correctly that be used to populate the select field correctly.

Data I have is list of strings that I read from a text file. Data in text file is in following format.

['Afghanistan', 'Albania', 'Algeria']


I would like to iterate over these elements in jinja template and populate drop down list. My jinja template looks like this

<select name="country">
{% for country in countryList %}
<option value="">{{country}}</option>
{% endfor %}
</select>


I have tried something like this to read from file

with open(filename, 'r') as f:
data_list = f.read().replace('\n', ' ')
country_list = zip(data_list )

return render_template('signup.html', countryList= country_list)


but in jinja everything is read one character at a time.
I have tried this

lines = tuple(open(filename, 'r'))


But that doesn't solve the issue either. In select field I only see '['

Other things I have tried

with open(filename, 'r') as f:
array = []
for line in f:
array.append(line)


with open(filename, 'r') as f:
data_list = []
data_list = f.read().replace('\n', ' ')


I understand it is not Jinja or flask issue. But not sure how to read the data correctly from text file so that it is a list. Is there something I can try that could suggest problem with text file ?

Answer

Change the format of your input file to this:

Afghanistan
Albania
Algeria

Then your code becomes:

with open(filename, 'r') as f:        
    country_list = [line.strip() for line in f]

return render_template('signup.html', countryList= country_list)

Your template file should then work with no changes.

Comments