coderusher
coderusher

Reputation: 36

load words from file and make a list of that

My idea is to load words from a directory (contains A Words.txt- Z Words.txt) and copy it into a list. The below code works, but adds "\n" at the end of each word (example ["apple\n", "abort\n"]); can anybody suggest a way to fix it?

from io import *
import string

def load_words(base_dir):
words = []
for i in string.uppercase:
    location = base_dir+"\\"+i+" Words.txt"
    with open(location, "rb+") as f:
        words += f.readlines()
return words

Upvotes: 0

Views: 329

Answers (3)

falsetru
falsetru

Reputation: 368954

Explicitly strip newlines using str.rstrip:

def load_words(base_dir):
    words = []
    for i in string.uppercase:
        location = base_dir+"\\"+i+" Words.txt"
        with open(location, "rb+") as f:
            for line in f:                      # <---------
                words.append(line.rstrip())     # <---------
            # OR words.extend(line.rstrip() for line in f)
    return words

Upvotes: 1

WeaselFox
WeaselFox

Reputation: 7380

change

words += f.readlines()

to :

words += [x.strip() for x in f.readlines()]

strip() removes trailing and leading whitespace charachters.

Upvotes: 1

Arun Reddy
Arun Reddy

Reputation: 3733

Try this. Hope it helps.

from io import *
import string

def load_words(base_dir):
words = []
for i in string.uppercase:
    location = base_dir+"\\"+i+" Words.txt"
    with open(location, "rb+") as f:
        for i in f.readlines():
            words.append(i.strip())
return words

Upvotes: 0

Related Questions