john doe
john doe

Reputation: 2253

Problems converting an external .txt file into a List in Python?

I have a .txt file with some strings like this:

word_1
word_2
word_3
....
word_n
word_n-1

I would like to read them and place them into list, in order to do something like this:

my_words = set(['word_1',...,'word_n-1'])

This is what I tried:

with open('/path/of/the/.txt') as f:
   lis = set([int(line.split()[0]) for line in f])
   print lis

But I get this error:

    lis = set([int(line.split()[0]) for line in f])
ValueError: invalid literal for int() with base 10: '\xc3\xa9l'

What would be a better way to do this and how can I deal with the encoding of this extarnal .txt file?.

Upvotes: 0

Views: 38

Answers (1)

Marcin
Marcin

Reputation: 238139

I think you need something like this:

with open('file.txt') as f:
    lis = set(line.strip() for line in f)
    print lis

The result is:

set(['word_3', 'word_2', 'word_1', 'word_21', 'word_123'])

Upvotes: 1

Related Questions