-2

I want to save data in a csv file

I wrote this code

chemin = 'D:/Documents/prg5/'
NomFic= 'Datamat'
filepath = chemin + NomFic + '.csv'


file = open(filepath,"wb")
cw=csv.writer(file)

cw.writerow(("ALL"   "GP+G"   "GAMMA.PRIME"  "GP/G"))

for row in zip(choices0, PX, PA, C1*100):

    row = "%s %.2f %.2f %.2f" % row
    cw.writerow(row)            

file.close()

I would like to have my file with four columns with the same width the first column is 'NI, 'Co', 'Ti'.. the others are numeric with two decimal

DavidG
  • 24,279
  • 14
  • 89
  • 82
Patrice
  • 209
  • 1
  • 4
  • 15

1 Answers1

1

You can use str.format() as in:

For the header:

with open(filename, "w") as file:
    file.write("{0:<3}{1:<10}{2:<10}{3:<10}\n".format("ALL", "GP+G", "GAMMA.PRIME", "GP/G"))

For the data:

with open(filename, "a") as file:
    file.write("{0:<3}{1:10.2f}{2:10.2f}{3:10.2f}\n".format(var0, var1, var2, var3))

In these examples, the fields are not comma separated.

Denis
  • 76
  • 3