31.3.09

Python function to write tables with user-defined columns number to a text file:



def print_table(list, cols, file_name):

file = open(file_name,"w")
length = len(list)
i = 1
list.insert(0,-999.0)

while i <= length:
file.write("%7.1f " % float(list[i]))
if i % cols == 0: file.write("\n")
i = i + 1

file.write("\n")
file.close()



Example usage:



>> print_table(range(34),7,"data.dat")

0.0 1.0 2.0 3.0 4.0 5.0 6.0
7.0 8.0 9.0 10.0 11.0 12.0 13.0
14.0 15.0 16.0 17.0 18.0 19.0 20.0
21.0 22.0 23.0 24.0 25.0 26.0 27.0
28.0 29.0 30.0 31.0 32.0 33.0



PS. Blogger parser doesn't understand lines indents so beware

This snippet on pastebin: http://pastebin.com/f48f845e7

No comments: