Question

In: Computer Science

Build a module (file with pre-defined functions) that allows the following code to work properly. The...

Build a module (file with pre-defined functions) that allows the following code to work properly. The code below should be able to run without any additions or modifications. You may copy and paste it into a file called file_tools_assignment.py and place it in the same directory as the file you will create. The filename of the file you will create should be file_tools.py. The module should contain 2 custom defined functions; get_file_string() and get_file_list(). Download the data.txt file and place it in the same directory with your other two files.

Contents for file_tools_assignment.py:

import file_tools

filename = 'data.txt'

contents = file_tools.get_file_string(filename)
print(contents)

list_of_lines = file_tools.get_file_list(filename)
print(list_of_lines)

(5 points) The get_file_string() function should attempt to get the contents of a file and return it as a string. If no file exists, the return value should be None.

(5 points) The get_file_list() function should return a list where each element in the list corresponds to a line in the file. Note: no newline characters should be present in the elements of the list. Remove those before adding the elements to the list that gets returned. If no file exists, the return value should be an empty list.

Sample output (3 lines in data.txt):

hello world
    I love programming
Python rocks!

['hello world', '    I love programming', 'Python rocks!']

Solutions

Expert Solution

'''
Python version : 3.6
Python file : file_tools.py
Python program to create two functions that reads data from the file and return its contents
'''

def get_file_string(filename):
   ''' Function that reads the contents of the input filename and
   return the contents as a string '''
   try:
       file = open(filename) # open the file in read mode
       contents = file.read() # read the entire file contents and return it as a string
        return contents
   except IOError:
       # File error, return None
       return None
      
def get_file_list(filename):
   ''' Function that reads the contents of the input filename and
   return the contents as a list of strings where each element of
   the list corresponds to a line in the file'''
   try:
       file = open(filename) # open the file in read mode
       # read the contents of the file into the list with each line being an element of the list
       contents = file.readlines()
       # loop to remove the new line character from the end of all lines (except the last which doesn't contain any new line)
       for i in range(len(contents)-1):
           contents[i] = contents[i][:-1]
       return contents
   except IOError:
       # File error, return empty list
       return []
      
#end of file_tools.py

Code Screenshot:

'''
Python version : 3.6
Python file : file_tools_assignment.py
'''

import file_tools

filename = 'data.txt'

contents = file_tools.get_file_string(filename)
print(contents)

list_of_lines = file_tools.get_file_list(filename)
print(list_of_lines)

#end of file_tools_assignment.py

Code Screenshot:

Output:


Related Solutions

Change the code to sort list of strings without using any pre-defined functions Here is my...
Change the code to sort list of strings without using any pre-defined functions Here is my code: int n; String temp; Scanner in = new Scanner(System.in); System.out.print("Enter number of names you want to enter:"); n = in.nextInt(); String names[] = new String[n]; Scanner s1 = new Scanner(System.in); System.out.println("Enter all the names:"); for(int i = 0; i < n; i++){ names[i] = s1.nextLine(); } ***CHANGE THIS PART*** for (int i = 0; i < n; i++){ for (int j = i...
Python 3 Code does not save properly the data in the excel file. it stores the...
Python 3 Code does not save properly the data in the excel file. it stores the data in the same row over and over # required library import tkinter as tk from tkcalendar import DateEntry import xlsxwriter # frame window = tk.Tk() window.title("daily logs") #window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=3, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money...
Using the data set as a pre-defined variable in your program, write code that uses the...
Using the data set as a pre-defined variable in your program, write code that uses the dataset to print the first names of people who have BOTH above average math grades AND below average age from the dataset. The solutions for the textbook examples assume you are able to export in a framework like node.js, which is why in the data set I provide, I simply set the array of objects as a variable. Your code will be in the...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file must satisfy the following. Define a function named rinsert. This function will accept two arguments, the first a list of items to be sorted and the second an integer value in the range 0 to the length of the list, minus 1. This function shall insert the element corresponding to the second parameter into the presumably sorted list from position 0 to one less...
Write a Class called Module with the following attributes: module code, module name, list of lecturers...
Write a Class called Module with the following attributes: module code, module name, list of lecturers for the module (some modules may have more than one lecturer – we only want to store their names), number of lecture hours, and module description. Create a parameterised (with parameters for all of the class attributes) and a non-parameterised constructor, and have the accessor and mutator methods for each attribute including a toString method. Write a class Student with the following attributes: student...
Please write python code for the following. Implement the functions defined below. Include a triple-quoted comments...
Please write python code for the following. Implement the functions defined below. Include a triple-quoted comments string at the bottom displaying your output. Using sets (described in Deitel chapter 6) will simplify your work. Below is the starter template for the code: def overlap(user1, user2, interests): """ Return the number of interests that user1 and user2 have in common """ return 0    def most_similar(user, interests): """ Determine the name of user who is most similar to the input user...
Debug the code in the starter file so it functions as intended and does not cause...
Debug the code in the starter file so it functions as intended and does not cause any errors. This program is intended to take two integer inputs and determine whether the second is a multiple of the first or not. The number b is a multiple of the number a if b can be divided by a with no remainder. Remember though that no number can be divided by 0 - so no numbers should be considered a multiple of...
take the following html code and make it work for html validator. heres the ,html file...
take the following html code and make it work for html validator. heres the ,html file <!DOCTYPE html> <html lang="en">    <head>        <title> GettingStarted</title>        <meta charset="utf-8">        <link href="Style.css" rel="stylesheet">    </head>       <body>        <header><h1>GettingStarted</h1></header>        <nav>               <b>        <a href="Home.html">Home</a>&nbsp;        <a href="GettingStarted.html">Getting Started</a>&nbsp;        <a href="MaterialsNeeded.html">Materials Needed</a>&nbsp;                      <a href="TroubleShooting.html">TroubleShooting</a>&nbsp;        <a href="InfoMaterials.html">Infomation on materials</a>&nbsp;   ...
Create a C module convertTo_csv.c that will implement the function loadAndConvert(const char* file) The code must...
Create a C module convertTo_csv.c that will implement the function loadAndConvert(const char* file) The code must be split into 2 files (.h file and a .c file). The convertTo_csv.c will have the function implementation in ti and the The convertTo_csv.h file will have the declaration. One argument will be given to the function, that is the name of the input file that needs to be converted. A function will create a new csv file called output.csv Know that the loadAndConvert...
This is c++ code. Create a file sort.cpp. to mix functions with the selection sort algorithm:...
This is c++ code. Create a file sort.cpp. to mix functions with the selection sort algorithm: ·Write a function int least(vector<string> strs, int start)to return the index of the smallest value in the vector. You are to assume there is at least one value in the vector. ·Write a function void selsort(vector<string> & strs) to use selection sort to sort the vector of strings. It is a worthwhile experiment to try leaving out the & and seeing that the vector...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT