Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

data_management.py 2.1 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
  1. import json
  2. def read_data_from_file(file_path: str) -> str:
  3. """
  4. Reads data from a file and returns it as a string.
  5. :param file_path: Path to the file to be read.
  6. :return: Contents of the file as a string.
  7. """
  8. try:
  9. with open(file_path, 'r', encoding='utf-8') as file:
  10. return file.read()
  11. except FileNotFoundError:
  12. print(f"File not found: {file_path}")
  13. return None
  14. except Exception as e:
  15. print(f"Error reading from file: {e}")
  16. return None
  17. def write_data_to_file(file_path: str, data: str) -> bool:
  18. """
  19. Writes data to a file.
  20. :param file_path: Path to the file where data will be written.
  21. :param data: Data to be written to the file.
  22. :return: True if the operation is successful, False otherwise.
  23. """
  24. try:
  25. with open(file_path, 'w', encoding='utf-8') as file:
  26. file.write(data)
  27. return True
  28. except Exception as e:
  29. print(f"Error writing to file: {e}")
  30. return False
  31. def load_json_data(file_path: str) -> dict:
  32. """
  33. Loads data from a JSON file.
  34. :param file_path: Path to the JSON file.
  35. :return: Parsed JSON data as a dictionary.
  36. """
  37. try:
  38. with open(file_path, 'r', encoding='utf-8') as file:
  39. return json.load(file)
  40. except FileNotFoundError:
  41. print(f"JSON file not found: {file_path}")
  42. return {}
  43. except json.JSONDecodeError:
  44. print(f"Error decoding JSON from file: {file_path}")
  45. return {}
  46. except Exception as e:
  47. print(f"Error loading JSON data: {e}")
  48. return {}
  49. def save_json_data(file_path: str, data: dict) -> bool:
  50. """
  51. Saves data to a JSON file.
  52. :param file_path: Path to the JSON file where data will be saved.
  53. :param data: Data to be saved in JSON format.
  54. :return: True if the operation is successful, False otherwise.
  55. """
  56. try:
  57. with open(file_path, 'w', encoding='utf-8') as file:
  58. json.dump(data, file, indent=4)
  59. return True
  60. except Exception as e:
  61. print(f"Error saving JSON data: {e}")
  62. return False
  63. # Additional data management functions can be added as needed.
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...