-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.py
More file actions
101 lines (77 loc) · 2.62 KB
/
file.py
File metadata and controls
101 lines (77 loc) · 2.62 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
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
""" file.py """
import os
import json
def create_or_update(file_name: str, content: dict = None) -> None:
"""Create a new json file or Updates an existing file
Args:
file_name (str): File name or path
content (str, optional): Text file content. Defaults to None.
"""
if os.path.isfile(file_name):
if valid_json_file(file_name):
update(file_name, content)
else:
create(file_name, content)
else:
create(file_name, content)
def valid_json_file(file_name) -> bool:
try:
file = open(file_name)
json.loads(file.read())
file.close()
return True
except ValueError as e:
os.remove(file_name)
return False
def create(file_name: str, content: dict = None) -> None:
"""Create a new json file
Args:
file_name (str): File name or path
content (str, optional): Text file content. Defaults to None.
"""
mode = "w" if content else "x"
try:
file = open(file_name, mode)
except FileExistsError as error:
raise OSError(f"File '{file_name}' already exists") from error
except PermissionError as error:
raise OSError(f"You do not hav permisson to create '{file_name}'") from error
if content and isinstance(content, (list, dict)):
content = json.dumps(content)
file.write(content)
file.close()
def update(file_name: str, content: dict) -> None:
"""Updates an existing file
Args:
file_name (str): File name or path
content (str): Text file content
overwrite (bool, optional): If True, file will be overwritten. Defaults to False.
"""
if not isinstance(content, dict) or content == "":
raise ValueError("'content' argument must be specified")
file = open(file_name)
file_content = json.loads(file.read())
file.close()
if isinstance(file_content, list):
if isinstance(content, dict):
file_content.append(content)
elif isinstance(content, list):
file_content += content
elif isinstance(file_content, dict):
if isinstance(content, dict):
file_content = [file_content, content]
elif isinstance(content, list):
file_content = [file_content] + content
file = open(file_name, "w")
file.write(json.dumps(file_content))
file.close()
def read(file_name: str) -> str:
"""Returns the content of a text file
Args:
file_name (str): File name or path
Returns(str): File content
"""
file = open(file_name)
content = file.read()
file.close()
return content