I am making a function that accepts a plain text file and then returns a list of words in that file. Obviously, I would like to get rid of any newline '\n', however, when using '.replace()' nothing happens.
Function:
textfile = 'name.txt'
def read_words(filename):
f = open(filename,'r')
message = f.read()
a = message.replace('\n', '')
wordlist = a.split(' ')
print(wordlist)
read_words(textfile)
Sample txt:
This\n\nis\n\n\na\n\n\nmy\n\nwfile with spaces and blanks
My output:
['This\\n\\nis\\n\\n\\na\\n\\n\\nmy\\n\\nwfile', 'with', 'spaces', 'and', 'blanks']
Why is the '.replace()' method not working?
replacemethod is certainly working. What's your expected output?'.replace()'method not working? Show us the output that makes you think it isn't working. You've only shown us the sample file contents, which doesn't demonstrate anything.This\n\nis\n\n\na\n\n\nmy\n\nwfile with spaces and blanks, or are you replacing the newlines with\nfor us? If the former, you'll need to escape the backslash in your replace:message.replace('\\n', '')