import json
def read_last_line(file_path: str)->str:
with open(file_path, 'r') as myfile:
file_content = myfile.read().splitlines()
if len(file_content) > 1:
return file_content[-1]
else:
return ""
def read(file_path: str)->str:
with open(file_path, 'r') as myfile:
file_content= myfile.read()
if len(file_content) > 1:
return file_content
else:
return ""
def write(file_path:str, text:str=‘’):
with open(file_path, 'a+') as myfile:
myfile.write(text)
def write_last_line(file_path:str, text:str=‘’):
with open(file_path, 'a+') as myfile:
myfile.write('\n' + text)
def clear(file_path: str):
json.remove(file_path)
print("The file has been removed.")
def delete_last_line(file_path: str) → str:
with open(file_path, "r") as file:
data = file.read().splitlines()
if len(data) > 0:
with open(file_path, "w") as myfile:
for line in data[:-1]:
myfile.write(line + "\n")
return data[-1]
else:
return ""
def swap_value(file_path: str, key: str, replacement):
with open(file_path, 'r') as myfile:
file_content = (myfile.read())
old_value = file_content[key]
file_content[key] = replacement
file_content = json.dumps(file_content, indent = 4)
print("File after swapping the values is below: ", '\n', file_content)
with open(file_path, 'w') as myfile:
myfile.write(str(file_content))
return old_value
def update_transactions(file_path: str, transaction_list: list):
with open(file_path, ‘r’) as myfile:
transaction = (myfile.read())
print(“Old transaction list: {}”.format(transaction))
class Transaction:
def init(self, id:int, type:str, amount:float):
self.id:int = id
self.type:str = type
self.amount:float = amount
def __str__(self):
return f'Transaction[{self.id}] {self.type} ${self.amount}'
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
return hasattr(other,'id') and other.id == self.id
def check_duplicate_enteries(self, TransactionList):
for i, j, k in TransactionList:
if i == self.id:
TransactionList[j] = self.type
TransactionList[k] = self.amount
def add_new_entry(self):
entry = {}
entry['id'] = self.id
entry['type'] = self.type
entry['amount'] = self.amount
return entry
new_transaction = Transaction(*transaction_list)
entry = new_transaction.add_new_entry()
for trans in transaction[“TransactionList”]:
if trans[“id”] == entry[‘id’]:
transaction[“TransactionList”].remove(trans)
print(“You were trying to add duplicate record. Duplication is removed.”)
(transaction[“TransactionList”]).append(entry)
with open(file_path, ‘w’) as myfile:
newEntry = json.dumps(transaction, indent = 4)
print(“Transaction list after updation: {}”.format(newEntry))
myfile.write(str(newEntry))
tran.json
{
“TransactionList”: [
{
“id”: 1234,
“typeOfTransaction”: “check”,
“amount”: 1000
},
{
“id”: 4567,
“typeOfTransaction”: “withdrawals”,
“amount”: 1500
},
{
“id”: 8910,
“typeOfTransaction”: “check”,
“amount”: 5000
},
{
“id”: 1112,
“type”: “withdrawals”,
“amount”: 9000
}
]
}