Search code examples
pythonlistfile-iowhitespacestrip

Is there a shorter way to remove line breaks when reading from a file to a list?


Here is my current code:

dfile = open('dictionary.txt', 'r')
sfile = open('substrings.txt', 'r')
dictionary_words = []
substrings = []

for line in dfile:
    dictionary_words.append(line.rstrip('\n'))
for line in sfile:
    substrings.append(line.rstrip('\n'))

It works but seems pretty wordy.

Is this the appropriate way to write this out, or am I missing a simpler process?


Solution

  • Try this:

    with open('dictionary.txt', 'r') as f:
        dictionary_words = f.read().splitlines()