2

Hi i have a python script that creates a single html file and i cannot figure out how to add javascript into it

import pathlib
import os
 
html = ""
 
for file in pathlib.Path(".").iterdir():
    if file.is_file():
        if str(file).endswith(".png"):
            html += f"<center><img src='{file}'/ height=100%></center><br>"
            
 
with open("index2.html", "w") as outputfile:
    outputfile.write(html)
 
os.startfile("index2.html")

So far ive tried

import pathlib
import os
 
html = ""
 
for file in pathlib.Path(".").iterdir():
    if file.is_file():
        if str(file).endswith(".png"):
            html += f"<center><img src='{file}'/ height=50%></center><br><script>var imagesrc = document.getElementById("image.png").src;"

 
with open("index2.html", "w") as outputfile:
    outputfile.write(html)
 
os.startfile("index2.html")

but that doesnt seem to work at all

Any help would be appreciated thanks

2 Answers 2

1

Lets say you have a script.js file in your directory:

# File.py
html += "<script type=\"text/javascript\" src=\"script.js\"></script>"

If you want it directly in the .html file, you can do this:

html += f"<script type=\"text/javascript\">{javascript_content}</script>"

 

Sign up to request clarification or add additional context in comments.

2 Comments

Im trying to get it into just one html file if possible
In this case you only have to copy-paste the code into a script tag, I'm editing my answer
0

That probably didn't worked because your " (quotation mark) is interrupting your string at "image.png", you could use a single apostrophe, or just escape it using backslash.

html += f"<center><img src='{file}'/ height=50%></center><br><script>var imagesrc = document.getElementById(\"image.png\").src;"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.