Question

In: Computer Science

def read_words(filename, ignore='#'): """ Read a list of words ignoring any lines that start with the...

def read_words(filename, ignore='#'):
""" Read a list of words ignoring any lines that start with the ignore character as well as any blank lines. """
return ['a', 'z']

How would I code this in Python?

Solutions

Expert Solution

#function for readwords

#input: filename adn ignore char

#returns a list of all lines

def read_words(filename,ignore='#'):

#open file in read mode

f = open(filename,'r')

#read all the lines from file

allLines = f.readlines()

#initialize an array to store our result

ListofLines = []

#iterate through each line

for line in allLines:

#if it is not an empty line and if it does'nt have # append to our list

if(line != '\n' and line.find('#') != 0):

ListofLines.append(line.rstrip('\n'))

return ListofLines

print(read_words('test.txt',ignore='#'))

----------------------------------------------------------------------------------------------------
Your ThumbsUp on this answer matters to me a lot :)
----------------------------------------------------------------------------------------------------
For any further clarifications, Please do not hesitate to reach out in the comments section


Related Solutions

In python def lambda_2(filename): # Complete this function to read grades from `filename` and map the...
In python def lambda_2(filename): # Complete this function to read grades from `filename` and map the test average to letter # grades using map and lambda. File has student_name, test1_score, test2_score, # test3_score, test4_score, test5_score. This function must use a lambda # function and map() function. # The input to the map function should be # a list of lines. Ex. ['student1,73,74,75,76,75', ...]. Output is a list of strings in the format # studentname: Letter Grade -- 'student1: C' #...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT