twigg
twigg

Reputation: 3993

python best way to output larges amount of formatted text

I'm trying to think of the best way to write large amounts of formatted text in python to a text file. I'm creating a tool that generates PHP files automatically depending on user input.

The only way my limited knowledge of python can come up with at the moment is write each line individually to the file like so:

print("    <html>", file=f)
print("        <head>", file=f)
print("        </head>", file=f)
print("        <body>", file=f)
.....

The skeleton of the document I print to the file like above and add in variables the user supplies via raw_input such as page title, meta data etc

What would be a better way of doing this?

I suppose what I would be looking for is something similar to pythons commenting systems like this:

"""
page contents with indentation here + variables
"""

Then write this out to a file

Upvotes: 0

Views: 769

Answers (4)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

what you call "python commenting system" is NOT a "comment system" - comments start with a "#" -, it's a syntax for multiline strings. The fact that it's also used for docstrings (which are not comments but documentation and become attributes of the documented object) doesn't make it less of a proper python string. IOW, you can use it for simple templating:

tpl = """
<html>
    <head>
    </head>
    <body>
        <h1>Hello {name}</h1>
    </body>
</html>
"""
print tpl.format(name="World")

but for anything more involved - conditionals, loops, etc - you'd better use a real templating system (jinja probably being a good choice).

Upvotes: 2

tmdavison
tmdavison

Reputation: 69173

if you have all the lines stored in a list, you could iterate on the list:

# create lines however you want, put them in a list
linelist = ["    <html>", "        <head>", "        </head>", "        <body>"]

# open file
f=open('myfile.txt','w')

#write all lines to the file
for line in linelist:
    # Add a newline character after your string 
    f.write("".join([line,"\n"]))

f.close()

Or, more succinctly:

linelist = ["    <html>", "        <head>", "        </head>", "        <body>"]

f=open('myfile.txt','w')
f.write("\n".join(linelist))
f.close()

Upvotes: 1

dlask
dlask

Reputation: 8992

We can write output data line by line:

with open("test1.txt", "wt") as f:
    for i in range(1000000):
        f.write("Some text to be written to the file.\n")

and it takes some time to execute:

$ time python test1.py

real    0m0.560s
user    0m0.389s
sys     0m0.101s

Or we can prepare the whole output in memory and then write it at once:

r = []
for i in range(1000000):
    r.append("Some text to be written to the file.\n")
with open("test2.txt", "wt") as f:
    f.write("".join(r))

The execution time is different:

$ time python test2.py

real    0m0.433s
user    0m0.252s
sys     0m0.100s

Simply said, operations in memory are usually faster than operations with files.

Upvotes: 1

WoJ
WoJ

Reputation: 30035

You should consider looking at Python templating. This will allow you to enrich your preexisting data with variables (per your comment and update of the question).

Upvotes: 2

Related Questions