In: Computer Science
Use Python to Load a file containing a list of words as a python list :param str filename: path/name to file to load :rtype: list
Code two ways to do the same thing and commented one way. Uncomment whichever method you wish to use.
Please refer attached screenshot if you face any indentation errors.
#------Code_Begin-------
def read_file(filename):
'''
Method to read a file and convert words into a Python list
:param str filename: path/name to file to load
:rtype: list
'''
#Method1: Use open function to load a file and readlines in it and
append to a list.
#file_handler = open(filename,"r")
#words_list = []
#for line in file_handler.readlines():
# words_list.append(line.strip("\n"))
#file_handler.close()
#Method2: Use with context managaer which will open and close
automatically
with open(filename,"r") as file_handler:
words_list = []
for line in file_handler.readlines():
words_list.append(line.strip("\n"))
return words_list
#Sample output:
filename = "/Users/some_file.txt"
print(read_file(filename))
#------Code_End-------