Import contents of Text file into a List in Python

This is Regarding the projecteuler problem 42. I want to import the content of this text file (https://projecteuler.net/project/resources/p042_words.txt) in to a list in python.

I want the list to be like list = ["A","ABILITY",........] Any help is greatly appreciated.

Upvotes: 0

Views: 108

Answers (3)

Niall Cosgrove
Niall Cosgrove

Reputation: 1303

The values in the file are comma separated so you can use the csv reader. It will take care of everything for you.

import csv

with open('p042_words.txt', 'r') as infile:
    lst = [item for item in csv.reader(infile)][0]

the [0] is because there is only one line in the CSV file.

lst will now contain:

['A', 'ABILITY', 'ABLE', 'ABOUT', ...

Upvotes: 0

Ahmad
Ahmad

Reputation: 910

use following code:

mylist=[]
with open('p042_words.txt','r') as f:
    mylist=f.readlines()
l=[]
for i in mylist:
    l=l+i.split(',')
print(l)

if you want remove '"' character from each word use following code:

import re
mylist=[]
with open('p042_words.txt','r') as f:
    mylist=f.readlines()

l=[]
for i in mylist:
    j=re.sub('["]','',i)
    l=l+j.strip('"').split(',')
print(l)

Upvotes: 1

zwer
zwer

Reputation: 25779

You'll have to split the words once you load them, then strip the quotation marks from them to get the desired result, i.e.

with open("p042_words.txt", "r") as f:
    words = [word.strip("\"' \t\n\r") for word in f.read().split(",")]

print(words)
# ['A', 'ABILITY', 'ABLE', 'ABOUT', 'ABOVE', ...]

Technically, for this file simple stripping of quotation marks should be enough, but I've added the common whitespace and single quotation marks just in case.

Upvotes: 0

Related Questions