Skip to content

Commit b5e390b

Browse files
committed
Fix EmptyDataError when reading empty CSV files
1 parent 0f8e4ed commit b5e390b

1 file changed

Lines changed: 7 additions & 18 deletions

File tree

codecarbon/output_methods/file.py

Lines changed: 7 additions & 18 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)
@@ -96,30 +101,14 @@ def out(self, total: EmissionsData, _):
96101
if not file_exists:
97102
df = new_df
98103
elif self.on_csv_write == "append":
99-
try:
100-
df = pd.read_csv(self.save_file_path)
101-
except pd.errors.EmptyDataError:
102-
logger.warning(
103-
f"File {self.save_file_path} exists but is empty. Creating new file."
104-
)
105-
df = new_df
106-
df.to_csv(self.save_file_path, index=False)
107-
return
104+
df = pd.read_csv(self.save_file_path)
108105
# Filter out empty or all-NA columns, to avoid warnings from Pandas,
109106
# see https://github.com/pandas-dev/pandas/issues/55928
110107
df = df.dropna(axis=1, how="all")
111108
new_df = new_df.dropna(axis=1, how="all")
112109
df = pd.concat([df, new_df])
113110
else:
114-
try:
115-
df = pd.read_csv(self.save_file_path)
116-
except pd.errors.EmptyDataError:
117-
logger.warning(
118-
f"File {self.save_file_path} exists but is empty. Creating new file."
119-
)
120-
df = new_df
121-
df.to_csv(self.save_file_path, index=False)
122-
return
111+
df = pd.read_csv(self.save_file_path)
123112
df_run = df.loc[df.run_id == total.run_id]
124113
if len(df_run) < 1:
125114
df = pd.concat([df, new_df])

0 commit comments

Comments
 (0)