Reputation: 2629
What is the best method to create a neat tabular output and also save it the same way into text file ?
Right now I am displaying my output onto IPython console with the following code which provides an output as shown in Figure(1).
outputLine = ["NIST line CG100 CG050 FactoryCal HMFW (nm)-original (SIGMA) WCalFunctionDerivatives"]
for n, line in enumerate(wlines, 1):
outputLine.append(" ".join(
[str(item) for item in [wlines[n-1],peaks[n-1].cg100(),
peaks[n-1].cgArb(0.5),
wavelengthToPixel(wlines[n-1], 500, wavep),
peaks[n-1].getHMFW() / prismpy.wcalfunctionDerivative(results.x, wlines[n-1]), peaks[n-1].getHMFWPixels(), prismpy.wcalfunctionDerivative(results.x, wlines[n-1])]]))
Coming from a Mathematica background, what other methods can I use to display this same output in a neat tabular format ? Thanks in advance.
Upvotes: 0
Views: 173
Reputation: 46759
If you are working with a list of lists, the following approach might be useful:
def col_display(data, file):
widths = [0] * len(data[0])
for row in data:
widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)]
for row in data:
output = " ".join(["%-*s" % (widths[index], col) for index, col in enumerate(row)])
print(output)
file.write(output + '\n')
outputLine = ["NIST line", "CG100", "CG050", "FactoryCal", "HMFW (nm)-original", "(SIGMA)", "WCalFunctionDerivatives"]
wlines = [[123.1234567890] * 7] * 4
lines = [outputLine] + wlines
with open('output.txt', 'w') as f_output:
col_display(lines, f_output)
Which would display the following, and create a text file with the same contents:
NIST line CG100 CG050 FactoryCal HMFW (nm)-original (SIGMA) WCalFunctionDerivatives
123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789
123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789
123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789
123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789 123.123456789
Upvotes: 1