0

I have to print some results from a python analysis to a strict character formatting text file. What I have is a line like this

Correct
0 1049 1  0  2.18
Wrong
0 1049 1  0 2.18

where I have a code writing the lines out in this manner

df = pd.DataFrame(*** some data ***)
f = open("outfile.txt", "w")
for idx, row in df.iterrows():
   print(" 1 {:<4} 3  0 {:2.2f}".format(row['serial'], row['time']), file=f)
f.close

But what ends up happening is my last variable (row['sensor']), is often a float that has a single integer (0-9), and when it prints, I loose the leading space that I need. But this is not always true, sometimes the (row['sensor']) can be a 2 digit int such as 12.28. How do I make this print to save the leading space when it is required? Any help on formatting this would be greatly appreciated.

  • Yes it does. I came across this earlier, but didn't realize that what I needed to do was change the {:2.2f} to {:5.2f}. I actually tried it earlier with {:4.2f} thinking that it was accounting for numbers, not realizing that the decimal goes into the character count as well, so it kept shifting my numbers. Thank you for the help! – SumGuyzClone Nov 15 '21 at 15:15

0 Answers0