In: Computer Science
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!']
'''
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: