Python: load words from file into a set Python: load words from file into a set python python

Python: load words from file into a set


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')))