Mauro
Mauro

Reputation: 21

Shortening code for formatted output

I must write a two dimensional array (let's say array[100][20]) into a file. This is just an example of my code:

for i in range(0,99):
  print >> file, "%15.9e%24.15e%3d..." % (array[i][0], array[i][1], array[i][2], ... )

Is it possible to shorten it after "%" symbol with a slicing or something similar notation?

Upvotes: 2

Views: 114

Answers (2)

mgilson
mgilson

Reputation: 309949

You could do:

print >> file, format_string % tuple(array[i])

That said, I think that I would probably use numpy here to save the data in a format that isn't ascii for efficiency (both in terms of time spent doing IO and disk space).

Upvotes: 3

BenDundee
BenDundee

Reputation: 4521

At the risk of being down-voted, are you sure you're asking the right question? I've always found that if something is ugly or hard, it's probably not the best approach, especially in Python.

You might check out the csv module---what format do you want to write, exactly?

There's also the texttable module, that makes pretty tables for you, and will even dump them to a text file.

Finally, if you should be so inclined, there are the Python Excel Utilities, which will dump things into Excel spreadsheets. I have written some wrappers around the excel read and excel write interfaces in that module that I'll post here if you want---they're nothing special, but they may save you some time.

Upvotes: 2

Related Questions