Spaces:
Build error
Build error
Create file_utils.py
Browse files- file_utils.py +47 -0
file_utils.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
import pandas as pd
|
| 3 |
+
|
| 4 |
+
def load_service_data(file_path: str) -> pd.DataFrame:
|
| 5 |
+
"""
|
| 6 |
+
Loads a CSV file into a Pandas DataFrame and sets the index to the 'service' column.
|
| 7 |
+
|
| 8 |
+
Parameters:
|
| 9 |
+
file_path (str): Path to the CSV file.
|
| 10 |
+
|
| 11 |
+
Returns:
|
| 12 |
+
pd.DataFrame: DataFrame with 'service' as the index.
|
| 13 |
+
"""
|
| 14 |
+
try:
|
| 15 |
+
df = pd.read_csv(file_path)
|
| 16 |
+
df = df.set_index("service") # Set 'service' as index
|
| 17 |
+
return df
|
| 18 |
+
except FileNotFoundError:
|
| 19 |
+
print(f"Error: The file '{file_path}' was not found.")
|
| 20 |
+
return pd.DataFrame() # Return an empty DataFrame on error
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"Error loading CSV file '{file_path}': {e}")
|
| 23 |
+
return pd.DataFrame()
|
| 24 |
+
|
| 25 |
+
def load_pickle(file_path: str):
|
| 26 |
+
"""Loads and returns data from a Pickle (.pkl) file."""
|
| 27 |
+
try:
|
| 28 |
+
with open(file_path, "rb") as file: # Open in 'rb' (read binary) mode
|
| 29 |
+
return pickle.load(file)
|
| 30 |
+
except FileNotFoundError:
|
| 31 |
+
print(f"Error: The file '{file_path}' was not found.")
|
| 32 |
+
return None
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"Error reading Pickle file '{file_path}': {e}")
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
def load_file(file_path: str) -> str:
|
| 38 |
+
"""Reads the text from a file safely."""
|
| 39 |
+
try:
|
| 40 |
+
with open(file_path, "r", encoding="utf-8") as file:
|
| 41 |
+
return file.read()
|
| 42 |
+
except FileNotFoundError:
|
| 43 |
+
print(f"Error: The file '{file_path}' was not found.")
|
| 44 |
+
return ""
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"Error reading file '{file_path}': {e}")
|
| 47 |
+
return ""
|