Question

Please create a python module named homework.py and implement the functions outlined below. Below you will...

Please create a python module named homework.py and implement the functions outlined below. Below you will find an explanation for each function you need to implement. When you are done please upload the file homework.py to Grader Than. Please get started as soon as possible on this assignment. This assignment has many problems, it may take you longer than normal to complete this assignment.

This assignment is supposed to test you on your understanding of reading and writing to a text file and working with JSON objects.

Hint: Work on the methods in the order they are found in the documentation below.

def read_last_line(file_path: str)->str:
    """
    Reads the last line of the file at the specified file path. The function returns the last line of the file as a
    string, if the file is empty it will return an empty string ("").
    :param file_path: A path to a file
    :return: The last line of the file
    """
def read(file_path: str)->str:
    """
    Reads the entire file at the specified file path. The function returns all the text in the file as a string, if
    the file is empty it will return an empty string ("").
    :param file_path: A path to a file
    :return: All the text in the file
    """
def write(file_path:str, text:str=''):
    """
    Clears the file at the specified file path then writes the specified line to the file. If the function is invoked
    without a line parameter or the line variable is None nothing is written to the file but the file should still be
    cleared. If the file does not exist a new file is created, regardless if a text is specified.
    :param file_path: A path to a file
    :param line: None
    :return:
    """
def write_last_line(file_path:str, text:str=''):
    """
    Writes the specified line to the file as the last line. If the text parameter does not start with a new line
    character this adds a new line character to the text parameter so that the text is written on the next line of
    the file. If the function is invoked without a line parameter or the line variable is None nothing is written to
    the file. If the file does not exist a new file is created, regardless if a text is specified.
    :param file_path: A path to a file
    :param text: The last line to be written to the file.
    :return: None
    """
def clear(file_path: str):
    """
    Clears the file at the specified file path.
    :param file_path: A path to a file
    :return: None
    """
def delete_last_line(file_path: str) -> str:
    """
    Removes the last line in the file at the specified file path. Then it saves the new value with the last line
    removed to the file. Finally it returns the deleted last line. If the file has nothing in it an empty
    string ("") is returned.
    :param file_path: A path to file
    :return: The text in the file with the last line removed
    """
def swap_value(file_path: str, key: str, replacement):
    """
    This function will be given a file path and a key. The file that the file path points to contains a json object.
    This function should, load the data in the file. Then replace the value associated with the key with replacement
    value. Then it should overwrite the current data in the file with the new changes. Finally it should return the
    old value.

    :param file_path: A path to file
    :param key: A key value in the JSON object saved in the file
    :param replacement: The new value that the key will be mapped to
    :return: The old value that the key used to be mapped to
    """
def update_transactions(file_path: str, transaction_list: list):
    """
    You are part of a team tasked to create an application that helps bankers by saving their transactions for them.
    Your job within the project is to implement the feature that actually saves the transactions to the hard drive.
    The scope of your task is that you will be given a file path to where the data should be written and a list of
    bank transaction objects to be written to the file. The file will contain a JSON array of transactions that the
    banker previously saved. The bankers at this bank are silly sometimes and they make duplicate transactions, your
    function should remove the duplicate transactions in the transaction_list and update the existing transaction list
    saved in the file with the new transactions. Make sure when you are preforming the update of the new transactions
    that you overwrite old transactions (transactions that already exist in the file) with duplicate new transactions
    (transactions that are found in the transaction_list). You will know that a transaction is a duplicate if it has
     the same ID.

    In the end the file should contain a JSON list with transaction Objects that have been updated with the new
    information from the transaction_list. The JSON list should contain no transactions with the same ID.

    The transaction object referred to here in is outlined below. In actual testing of your code the professors
    transaction object will be used, which will have all the documented functionality.

    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 'Transaction[%s] %s $%s' (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

    :param file_path: A path to file blank file that holds a JSON list of existing transaction and where the new
     transaction data should be written
    :param transaction_list: A list of transaction
    :return: None
    """

I am new for this and I don't know how to create a file and all the things talked about here. I need help. thank you in advance

Homework Answers

Answer #1

IN PYTHON WE CAN CREATE A FILE BY USING THE OPEN() METHOD WITH "w" ACCESS SPECIFIER :

IN FILES , ACCESS SPECIFIER SPECIFIES THE TYPE OF OPERATION (READ ,WRITE , APPEND ) THAT WE ARE GOING TO PERFORM ON THE FILE.

THE CODE BELOW CONTAINS ALL THE METHODS ASKED IN THE QUESTION :

# here notice the "r" access specifier to read the file
# readllines() method returns a list of all the lines in the file
#using the negative indexing , reading the last line 
def read_last_line(path):
    with open(path,"r") as f1:
        lines = f1.readlines()
        res = lines[-1]
        return res

# read() method returns all the content of a file in the form of string
def read_file(path):
    with open(path,"r") as f1:
        f1.read()
        f1.close()  

#here notice that "w" access specifier is used to write into a file
# All the contents will be erased and new content will be added
# Here "text" is written into file
 
def write_file(path,text):
    with open(path,"w") as f2:
        f2.write(text)
        f2.close()

# here notice that "a" access specifier is used to append content to a file
# appending means writing to the last line of the file 
def write_last_line(path,text):
    with open(path,"a") as f1:
        f1.write(text)
        f1.close()

# for clearing the content of the file , we use the truncate() method 
def clear(path):
    with open(path,"r") as f1:
        f1.truncate()
        f1.close()


def delete_last_line(path):
    with open(path,"r") as f1:
        d=f1.read()
        f1.close()
        m= d.split("\n")
        s= "\n".join(m[:-1])
        f1 = open("file.txt","w+")
        for i in range(len(s)):
            f1.write(s[i])
        f1.close()
def swap_values(path,key,replacment):
    with open(path , 'w') as f1:
        for line in inp:
            if line == key:
                out.write(line)
                continue
            else:
                out.write(prev)
                prev = line
    f1.close()

The update transactions method :

import json
def update_transactions(path,transactions):
    # Searching for a duplicate id value in the transactions list and removing it
    # Notice that we use a dictionary to  filter the duplicates because dictionary does not allow the 
    # duplicate values  
    unique = { each['id'] : each for each in transactions }.values()
    # dump() in json package is used to write the json list to a file
    # indent specifies the spacing that's required when writing json to the file
    with open(path, 'w', encoding='utf-8') as f1:
        json.dump(unique, f, ensure_ascii=False, indent=4)
    f1.close()

json package in python is used to perform operations relations to json objects.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
def clear(file_path: str): """ Clears the file at the specified file path. :param file_path: A path...
def clear(file_path: str): """ Clears the file at the specified file path. :param file_path: A path to a file :return: None """ def delete_last_line(file_path: str) -> str: """ Removes the last line in the file at the specified file path. Then it saves the new value with the last line removed to the file. Finally it returns the deleted last line. If the file has nothing in it an empty string ("") is returned. :param file_path: A path to file...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the SLLNode class from Lab 2: ○ top_node → SLLNode object or None ○ size → int, keep track of stack size ● Implement the push( ), pop( ), top( ) methods ● Use SLLNode methods: get_item( ), set_item( ), get_next( ), set_next( ) ● (5 pts) In push(item): ○ Create new SLLNode with item ○ Add new node before top node ○ Update top_node...
PYTHON : Create a Email Address Parser (* Please do make comments*) Often times, you may...
PYTHON : Create a Email Address Parser (* Please do make comments*) Often times, you may be given a list of raw email addresses and be asked to generate meaningful information from such a list. This project involves parsing such a list and generating names and summary information from that list. The script, eparser.py, should: Open the file specified as the first argument to the script (see below) Read the file one line at a time (i.e., for line in...
Python Programming Build a python programming that asks the user for a three-letter substring. The program...
Python Programming Build a python programming that asks the user for a three-letter substring. The program should then proceed to read the file strings.txt. Each line in strings.txt will contain a string. Your program should then test to see how many non-overlapping occurrences of the three-letter substring occur in that string and test whether the string is a palindrome. The program should then proceed to create an output file string_stats.txt, which contains the original data on one line and the...
please use linux/unix command terminal to complete, step 1 1-create a new directory named by inlab4...
please use linux/unix command terminal to complete, step 1 1-create a new directory named by inlab4 enter directory inlab4 create a new file named by reverse.c with the following contents and then close the file: /*reverse.c */ #include <stdio.h> reverse(char *before, char *after); main() { char str[100]; /*Buffer to hold reversed string */ reverse("cat", str); /*Reverse the string "cat" */ printf("reverse(\"cat\")=%s\n", str); /*Display result */ reverse("noon", str); /*Reverse the string "noon" */ printf("reverse(\"noon\")=%s\n", str); /*Display result */ } reverse(char *before,...
Please write a python code for the following. Use dictionaries and list comprehensions to implement the...
Please write a python code for the following. Use dictionaries and list comprehensions to implement the functions defined below. You are expected to re-use these functions in implementing other functions in the file. Include a triple-quoted string at the bottom displaying your output. Here is the starter outline for the homework: d. def count_words(text): """ Count the number of words in text """ return 0 e. def words_per_sentence(text): return 0.0 f. def word_count(text, punctuation=".,?;"): """ Return a dictionary of word:count...
Please linked both files. For this assignment you need to create a ToDo list using Javascript,...
Please linked both files. For this assignment you need to create a ToDo list using Javascript, along with HTML and CSS. Begin by creating a HTML page called todo.html. Then create a Javascript file called todo.js and link it in to the HTML page using a script tag. All Javascript for the assignment must be in the separate file. (For CSS, feel free to include styles in a style block at the top of the HTML page, or to link...
Finish the CustomerAccountTransactions program that reads customer accounts receivable data from a file and then applies...
Finish the CustomerAccountTransactions program that reads customer accounts receivable data from a file and then applies a series of transactions to the accounts. Its main() method uses the CustomerAccounts class to manage a collection of CustomerAccount objects: reading customer accounts data & transactions, and obtaining a String showing the customer accounts data after the operations are complete. You will need to complete the readCustomerAccounts () and applyTransactions() methods in the CustomerAccounts class. First, please fill in your name in the...
Q1) Write a Python function partial_print, which takes one parameter, a string, and prints the first,...
Q1) Write a Python function partial_print, which takes one parameter, a string, and prints the first, third, fifth (and so on) characters of the strings, with each character both preceded and followed by the ^ symbol, and with a newline appearing after the last ^ symbol. The function returns no value; its goal is to print its output, but not to return it. Q2) Write a Python function called lines_of_code that takes a Path object as a parameter, which is...
Use Python to Complete the following on a single text file and submit your code and...
Use Python to Complete the following on a single text file and submit your code and your output as separate documents. For each problem create the necessary list objects and write code to perform the following examples: Sum all the items in a list. Multiply all the items in a list. Get the largest number from a list. Get the smallest number from a list. Remove duplicates from a list. Check a list is empty or not. Clone or copy...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT