1

I have a Python 3 script that reads all files with a certain name format for each month and adds them to an output (resulting in an excel CSV sheet).

#!/usr/bin/env python
import datetime
todo=[]
for year in range(2008,datetime.datetime.now().year):
    for month in range(1,13):
        todo += ["CoreDB-225269-REPORT_"+year+month+"01.dat"]

for name in todo:
    with open("results.csv", "w") as out_file:
        in_file=file(name,'r')
        record=in_file.readline()
        while len(record):
            out_file.write(name+",\t"+record)
            record=in_file.readline()

print("Read "+str(len(todo))+" files into report.")

As you seem each line of each monthly report get's added to results.csv file. However, problem I am having is that when I open result file it only has the most recent monthly report as entries.

What happening to other months report data? Where it go!

Tersosauros
  • 883
  • 1
  • 12
  • 22
  • You need to open your file in append mode. Use `a` instead of `w`. – Mazdak Apr 04 '16 at 13:52
  • I would also move `with open("results.csv", "w") as out_file:` outside the loop, since each iteration you append to the same file. – apr Apr 04 '16 at 13:54
  • You also aren't `close()`'ing the `in_file` you `open()`, and are using `with` inconsistently (*with* one file and not the other). – Tersosauros Apr 04 '16 at 13:56
  • `open("results.csv", "w")` ---> `open("results.csv", "a")` – Zombro Apr 04 '16 at 14:20

0 Answers0