You can read a text file using the open() and readlines() methods. To read a text file into a list, use the split() method. This method splits strings into a list at a certain character. In the example above, we split a string into a list based on the position of a comma and a space (“, ”).
Example 1: Converting a text file into a list by splitting the text on the occurrence of '. '. We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of the line('/n') with ' ' and split the text further when '.
The strip() method of strings removes whitespace from both ends.
set(line.strip() for line in open('filename.txt'))
Just load all file data and split it, it will take care of one word per line or multiple words per line separated by spaces, also it will be faster to load whole file at once unless your file is in GBs
words = set(open('filename.txt').read().split())
my_set = set(map(str.strip, open('filename.txt')))
To remove only the right hand spaces.
set(map(str.rstrip, open('filename.txt')))
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