Python Forum
find file not knowing the extension
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
find file not knowing the extension
#1
Hello Coders!

I'm a student and I'm trying to complete a project for my course. I'm creating a small blog and now I'm working on the recipe page. The project is in Python+Flask+MongoDB.

I could do almost everything, I'm just having problems with a file. I have the picture of the recipe in a folder, so let's say the file is:

"/static/images/5f034b69b91c57308938cf82.png"

The id 5f034b69b91c57308938cf82 is the object id in MongoDB, I renamed the file in that way when I added the recipe.

Now in HTML file, recipe.html, I'm trying to show also the image of the recipe, and I can get the name using {{recipe._id}} but I don't know the extension, it might be any image extension. How could I get the following?

<img src="/static/images/{{FILE+EXT}} alt="RecipePic" />

I know the file name but not the extension, and I'm finding it difficult since jinja2 is giving me always errors.

Thank you in advance!!! :D
Reply
#2
You could use this module form the standard lib: https://docs.python.org/2/library/imghdr.html
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
(Jul-07-2020, 12:47 PM)DeaD_EyE Wrote: You could use this module form the standard lib: https://docs.python.org/2/library/imghdr.html

Thank you but it looks that I already need to know the extension in this way, I know the file name but not the extension, then I cannot use it.

I'm also trying to create if, in this way:

                    {% set path = '/static/images/images/' + recipe._id|string + '.png' %}
                    {% if (os.path.isfile(path)) %}
                            <p>File EXISTS</p>
                    {% else %}
                            <p>File DO NOT EXISTS</p>
                    {% endif %}
But I keep receiving the following error:

jinja2.exceptions.UndefinedError
jinja2.exceptions.UndefinedError: 'os' is undefined

os is defined in the main.py file, maybe I must use a different syntax, but I'm a beginner, I have no idea how it needs to be done.
Reply
#4
Do you need to know the extension so you can open/select the file? How about pathlib?
or os.scandir?
Reply
#5
a quick fix would be to create a sub directory for both png and jpg, that way the path itself is the test

also, not sure how youre inserting / retrieving data from mongodb, but adding a "type" key value pair with the extension as the value could also be an easy way to test for the extension.
Reply
#6
(Jul-07-2020, 12:56 PM)Leon79 Wrote:
(Jul-07-2020, 12:47 PM)DeaD_EyE Wrote: You could use this module form the standard lib: https://docs.python.org/2/library/imghdr.html
Thank you but it looks that I already need to know the extension in this way, I know the file name but not the extension, then I cannot use it.

The first scentence:
Quote:The imghdr module determines the type of image contained in a file or byte stream.
If you had paid a little more attention, you should have seen, that I linked it for Python 2.7 (old) and that the file type is guessed by its content and not the extension.

Source code from Python 3.8: https://github.com/python/cpython/blob/3.../imghdr.py

I think it's better, if you use the detection of file content in your server code and not in the template.

import imghdr
import mimetypes
from base64 import urlsafe_b64encode


def convert_data_src(filecontent: bytes):
    """
    Detect image type, get the mime type and
    return a bas64 encoded src for img tags.
    """
    extension = imghdr.what(None, filecontent)
    if not extension:
        return ""
    mime = mimetypes.types_map.get("." + extension)
    return f"data:{mime};base64,{urlsafe_b64encode(filecontent).decode()}"
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
It's not working, I tried any kind of code, because it's not hard to solve. The problem is with Jinja, I'm missing something. I have also tried the following:

            <div id="recipe-cont-body">
                <div>
                    <h1>Ingredients:</h1>
                    
                    {% set cpath = os.getcwd() %}
                    {% set imagepath = '/static/images/' %}
                    {% set finalpath = cpath + imagepath %}
                    {% set listOfFiles = os.listdir(finalpath) %}
                    {% set pattern = recipe._id + ".*" %}
                    {% for entry in listOfFiles: %}
                        {% if fnmatch.fnmatch(entry, pattern): %}
                            {% print (entry) %}
                        {% endif %}
                    {% endfor %}
I always get the following error, but in main.py I imported os as first line. Just would like to remember that I'm using Python+Flask, this code is in recipe.html. I try for another hour, if I cannot manage I will simply put the filename+ext in MongoDB. Thank you.
jinja2.exceptions.UndefinedError
jinja2.exceptions.UndefinedError: 'os' is undefined
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  partial functions before knowing the values mikisDeWitte 4 536 Dec-24-2023, 10:00 AM
Last Post: perfringo
  FileNotFoundError: [WinError 2] The system cannot find the file specified NewBiee 2 1,496 Jul-31-2023, 11:42 AM
Last Post: deanhystad
  Cannot find py credentials file standenman 5 1,554 Feb-25-2023, 08:30 PM
Last Post: Jeff900
  selenium can't find a file in my desk ? SouAmego22 0 702 Feb-14-2023, 03:21 PM
Last Post: SouAmego22
  Find (each) element from a list in a file tester_V 3 1,157 Nov-15-2022, 08:40 PM
Last Post: tester_V
  what will be the best way to find data in txt file? korenron 2 1,128 Jul-25-2022, 10:03 AM
Last Post: korenron
  find some word in text list file and a bit change to them RolanRoll 3 1,482 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  Find and delete above a certain line in text file cubangt 12 3,354 Mar-18-2022, 07:49 PM
Last Post: snippsat
Question Help to find the largest int number in a file directory SalzmannNicholas 1 1,587 Jan-13-2022, 05:22 PM
Last Post: ndc85430
Thumbs Up [SOLVED] Find last occurence of pattern in text file? Winfried 4 4,307 Aug-13-2021, 08:21 PM
Last Post: Winfried

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020