bqui56
bqui56

Reputation: 2121

Difference between opening a file and using a module

Below, I print out the html for a form defined externally. Is there a difference in the way each string is retrieved and used in foo.py, other than the syntax? If so, in what circumstances would one method be preferred over the other? For example, would I be better off defining a number of html files in a module as strings and access them that way, as opposed keeping them in separate .html files and using open over and over?

mod.py

form = """\
<form type="POST" action="test.py">
   Enter something:<input type="text" name="somethign">
</form>
"""

form.html

<form type="POST" action="test.py">
   Enter something:<input type="text" name="something">
</form>

foo.py

import mod

print mod.form

with open('form.html', 'r') as form:
   print form.read()

Upvotes: 0

Views: 121

Answers (2)

Dmitrii Tokarev
Dmitrii Tokarev

Reputation: 137

Having .html files is better. Sure, you will have some overhead opening a file, reading its content and then closing it, but you'll have many advantages:

  • .html file can be edited by any person who knows HTML syntax.
  • .html files can be edited without restarting your program, it is very useful for services.
  • You can eliminate open/read/close overhead by introducing some caching technique.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

It's a lot easier for designers to edit discrete HTML files than to deal with HTML embedded in code.

Upvotes: 1

Related Questions