forked from ylavr/Travel-smarter-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrite_read_data_to_file.py
More file actions
41 lines (32 loc) · 1.22 KB
/
write_read_data_to_file.py
File metadata and controls
41 lines (32 loc) · 1.22 KB
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
import os
import json
def write_data_to_file(file_name: str, data: dict):
if os.path.exists(file_name):
try:
with open(file_name, 'r') as file:
existing_data = json.load(file)
except json.JSONDecodeError:
# If file is empty, initialize existing_data as an empty dictionary
existing_data = {}
else:
# If file doesn't exist, initialize existing_data as an empty dictionary
existing_data = {}
existing_data.update(data)
with open(file_name, 'w') as file:
json.dump(existing_data, file)
return existing_data
def read_data_from_file(file_name: str):
if os.path.exists(file_name):
try:
with open(file_name, 'r', encoding="utf8") as file:
existing_data = json.load(file)
except json.JSONDecodeError:
# If file is empty, initialize existing_data as an empty dictionary
existing_data = {}
else:
# If file doesn't exist, initialize existing_data as an empty dictionary
existing_data = {}
with open(file_name, 'w') as file:
json.dump(existing_data, file)
return existing_data
print(read_data_from_file('test.json'))