-1

I write output of my code into a .txt file. I need to put a header in the .txt file. Something like this:

id, width, height, weight
1     252    455      555
2     544    525      475
3     4752   2445     58.5 
4     452.3  125.2    1422.36

I wrote this code but it just writes the header each time that I write the numbers. I only need to write header once. The rest should be numbers. I was wondering how to do so?

header = "id, width, height, weight"
with open(outputFilename, 'a') as file_writer:
    file_writer.write(header + "\n")
    file_writer.close
    
    
output_string=f"{f1}, {f2},  {f3}, {f4}\n"
print(output_string)
with open(outputFilename, 'a') as file_writer:
    file_writer.write(output_string)
Happypumpkin pm
  • 83
  • 1
  • 10
  • first check if the file exists and if not then write the header. – Albin Paul Jan 25 '22 at 15:00
  • Why not take a "do not reinvent the wheel" approach and use the [`csv`](https://docs.python.org/3/library/csv.html) module instead? – accdias Jan 25 '22 at 15:01
  • `file_writer.close` does not close the file, and also it is not necessary to close the file yourself using the `with` block. It is best to remove this line of code entirely, as it serves no purpose and is only a distraction. – Karl Knechtel Jan 25 '22 at 15:04
  • Welcome to Stack Overflow. Please read [ask]. "I wrote this code but it just writes the header each time that I write the numbers." Please show more context. As far as I can tell, the code that you are showing only "writes the numbers" once. If the problem is that you have some code inside a loop, and the looping doesn't work the way you want it to, then you need to *show the loop* in order for others to diagnose the problem properly. Otherwise we have to *guess* based on the described symptoms. – Karl Knechtel Jan 25 '22 at 15:05

1 Answers1

0

You can check output file is empty or not, if the output file is empty, you write the header. You can see example here.

filesize = os.path.getsize(outputFilename)

if filesize == 0:
    header = "id, width, height, weight"
    with open(outputFilename, 'a') as file_writer:
            file_writer.write(header + "\n")
            file_writer.close
bao.le
  • 146
  • 1
  • 4