'No data written in to csv file. What's wrong in this class based approach?

I have a project in that I initialize two log files in a class using 'setup_image_and_model_folders' as follows.

results_header = ['Image count','File path','Wafer','Die','Name']

def setup_image_and_model_folders(self):
    self.open_results_log()

def open_results_log(self):
    # creating log file to write all inspected files
    log_file = open(self.logs_csv,'a')
    self.log_writer = csv.writer(log_file)
    
    #creating results log file which only includes metal detected
    csv_file = open(self.results_csv,'w')
    self.csv_writer = csv.writer(csv_file)
    if not os.path.exists(self.results_csv):
        self.csv_writer.writerow(results_header)

def write_results(self, data):
    self.csv_writer.writerow(data)

def write_logs(self, log):
    self.log_writer.writerow(log)

It creates the CSV files at two locations specified in the path. However, 'results_csv' is empty although I write the header. Also no matter how many times I call 'write_results' and 'write_logs', nothing gets written into the files.

This is the first time I am using the class-based approach to update files. If I write the same thing in one function, it works fine.

What is wrong here?



Solution 1:[1]

Maybe you forgot to close the file.

Try to store the csv_file as self.csv_file and run close(your_class_instance.csv_file) after writing.

If this solves the issue, try to rewrite your code so that it uses a context manager, via:

with open(path_to_file, "w") as file:
   ... write to file ...

then file will be closed automatically.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jarmod