0

i have a result folder in my static directory with nine images called 'result_1.jpg' to 'result_9.jpg' and i want to display them in the correct order in a grid on my html page.

Everything works fine, except the output order is completely random but always the same.

Here's my python snippet:

@app.route('/fResults/')
def show_fResults():
    imgs = os.listdir('static/results/')
    imgs = ['results/' + file for file in imgs]
    return render_template('fResults.html', imgs = imgs)

Here's my html snippet:

<div class="resultGrid">
    {% for img in imgs %}
    <div class="resultImages">
        <img id="results" src="{{ url_for('static', filename = img) }}" alt="{{loop.index}}">
    </div>
    {% endfor %}
</div>

And here is the html output:

html output

Is there a way to force it to use a given order?

Thank you in advance!

EDIT: Thanks to Epsi95 I was able to fix my problem.

@Epsi95 thank you very much!

MuckDuck
  • 17
  • 2

1 Answers1

0

The output of os.listdir is kinda random, but will actually not always be the same. It depends how your OS's file system is feeling when you ask it to give you the files.

What you have to do is sort the list yourself in your application. Python has an inbuilt sorting function called sorted().

You can use it like this:

@app.route('/fResults/')
def show_fResults():
    imgs = sorted(os.listdir('static/results/'))
    imgs = ['results/' + file for file in imgs]
    return render_template('fResults.html', imgs = imgs)

Now they will always be in the same sorted order, regardless of what order os.lisdir() returns them.

Jabrove
  • 718
  • 5
  • 13
  • 1
    `imgs.sort()` after list comprehension will be quite more efficient as it won't initialize extra list in memory. – Olvin Roght Aug 01 '21 at 17:00
  • That's true, but I kept the answer as close to his code as possible since they are just learning about sorting, so memory optimization probably not on their radar. – Jabrove Aug 01 '21 at 17:04