-1

I have a python file called writer.py and an index.html in the same directory.

In my python file i have following import:

from reader import titles, links
print("titles and links")
for i in range(min(len(titles), 10)):
    print("- {} ({})".format(titles[i], links[i]))

i now want to display a the first title of my array titles in my index.html file, which currently looks like this:

<!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <h1>{{ title }}</h1>
  </body>
</html>

How to do that?

Thanks in advance

Dru.Dru
  • 59
  • 7

1 Answers1

1

You can do it like this:

First you load filecontent of index.html. Then you replace {{ title }} with the title in list at index 0. After that you write the new filecontent back to the file.

from reader import titles, links
print("titles and links")
for i in range(min(len(titles), 10)):
    print("- {} ({})".format(titles[i], links[i]))

# Read in the file
with open('index.html', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('{{ title }}', titles[0])

# Write the file out again
with open('index.html', 'w') as file:
  file.write(filedata)

See: https://stackoverflow.com/a/17141572/8980073

Note: All occurrences of the specified phrase will be replaced, if nothing else is specified. But you can change this behavior, see string.replace string.replace(oldvalue, newvalue, count). So you could write filedata.replace('{{ title }}', titles[0], 1) for replacing only first occurrence.

Lukas
  • 446
  • 3
  • 11
  • Next time you try to set a different title, this will fail, as there is nothing left to replace... – Thierry Lathuille Apr 26 '23 at 08:25
  • If this is important to the user, of course you can use htmlparser http://docs.python.org/library/htmlparser.html or replace the `str.replace()` with regex like `filedata = re.sub('

    (.*?)

    ', '

    ' + titles[0] +'

    ', filedata)` then you have to use `import re` in the beginning.
    – Lukas Apr 26 '23 at 08:29
  • Maybe to solve this issue, you could read the first file as a template (having the file in a different folder: `with open('templates/index.html', 'r') as file :`) and still write to same `index.html` – Benbb96 Apr 26 '23 at 08:43