Skip to content

Commit d8b4f58

Browse files
authored
Merge pull request #995 from isztldav/fix/handle-empty-csv-files
Fix EmptyDataError when reading empty CSV files
2 parents 4462829 + 9cc0a54 commit d8b4f58

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

codecarbon/output_methods/file.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,11 @@ def out(self, total: EmissionsData, _):
8888
8989
"""
9090
file_exists: bool = os.path.isfile(self.save_file_path)
91+
if file_exists and os.path.getsize(self.save_file_path) == 0:
92+
logger.warning(
93+
f"File {self.save_file_path} exists but is empty. Treating as new file."
94+
)
95+
file_exists = False
9196
if file_exists and not self.has_valid_headers(total):
9297
logger.warning("The CSV format has changed, backing up old emission file.")
9398
backup(self.save_file_path)

tests/output_methods/test_file.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,30 @@ def test_file_output_out_update_file_exists_one_matchingrows(self):
173173
# file_output = FileOutput("test.csv", self.temp_dir, on_csv_write="append")
174174
# file_output.out(self.emissions_data, None)
175175

176+
def test_file_output_out_append_empty_file_exists(self):
177+
file_output = FileOutput("test.csv", self.temp_dir, on_csv_write="append")
178+
# Create an empty file
179+
with open(file_output.save_file_path, "w") as _:
180+
pass
181+
182+
# This should not raise an error
183+
file_output.out(self.emissions_data, None)
184+
185+
df = pd.read_csv(os.path.join(self.temp_dir, "test.csv"))
186+
self.assertEqual(len(df), 1)
187+
188+
def test_file_output_out_update_empty_file_exists(self):
189+
file_output = FileOutput("test.csv", self.temp_dir, on_csv_write="update")
190+
# Create an empty file
191+
with open(file_output.save_file_path, "w") as _:
192+
pass
193+
194+
# This should not raise an error
195+
file_output.out(self.emissions_data, None)
196+
197+
df = pd.read_csv(os.path.join(self.temp_dir, "test.csv"))
198+
self.assertEqual(len(df), 1)
199+
176200
def test_file_output_task_out(self):
177201
task_emissions_data = [
178202
TaskEmissionsData(

0 commit comments

Comments
 (0)