[Tutor] reading random line from a file
Tiger12506
keridee at jayco.net
Thu Jul 19 01:11:14 CEST 2007
> import os
> import random
>
> text = 'shaks12.txt'
> if not os.path.exists(text):
> os.system('wget http://www.gutenberg.org/dirs/etext94/shaks12.txt')
>
> def randline(f):
> for i,j in enumerate(file(f, 'rb')):
Alright. But put randline in a loop and you open a lot of file handles.
Thank goodness python has GB.
Seperate variable, open file at start, close file at end.
So the file is read every time you call randline. At least as far as the
line chosen.
Whereas my version only reads at absolute most twice the same line.
And it will run faster. Searching through the file lines to find the one
who's index matches i is time-consuming.
Yes, my version will favor longer lines, but I don't think that seriously
strict randomization is necessary?
IMHO, memory and speed are more important here. (You must forgive me a
little, I've been studying C and assembly)
I'm just proud of my function ;-)
JS
More information about the Tutor
mailing list