I have a text file which is named test.txt
. I want to read it and return a list of all words (with newlines removed) from the file.
This is my current code:
def read_words(test.txt):
open_file = open(words_file, 'r')
words_list =[]
contents = open_file.readlines()
for i in range(len(contents)):
words_list.append(contents[i].strip('\n'))
return words_list
open_file.close()
Running this code produces this list:
['hello there how is everything ', 'thank you all', 'again', 'thanks a lot']
I want the list to look like this:
['hello','there','how','is','everything','thank','you','all','again','thanks','a','lot']
Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
You can read a text file using the open() and readlines() methods. To read a text file into a list, use the split() method.
Python read file into list. To read a file into a list in Python, use the file. read() function to return the entire content of the file as a string and then use the str. split() function to split a text file into a list.
Depending on the size of the file, this seems like it would be as easy as:
with open(file) as f:
words = f.read().split()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With