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?.
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'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.