[Tutor] Reading elements in a file
Alan Gauld
alan.gauld at btinternet.com
Thu May 5 00:59:17 CEST 2011
"Jeff Peery" <jeffpeery at seametrics.com> wrote
> Import sting
Its lower case import and I've no idea what sting is! :-)
If its meant to be string you don't need it.
> delimiter = ‘.’
> f = open('words.txt', "r")
> lines = f.readlines()
> for line in lines:
> line_items = string.split(line,delimiter)
You don't need the readlines(), just do
with open('words.txt', "r") as f:
line_items = [line.split(',') for line in f]
The string methods are builtin and the string
module is really only needed for backwatds
compatibility these days.
Also this code returns a list of lists of words.
The original code threw away the words after each line.
If you want a single list of words the code would
look more like:
with open('words.txt', "r") as f:
for line in f:
line_items += line.split(',')
To the OP: If you want to get rid of the " signs
around your words you can use the strip()
method too.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list