Lorin wrote: > hey, i need a way to grab a reasonably random line from a text file in > python. > > I'm using a really lame 'read all the lines in and select one at random' > system right now, but i'd like something more efficient since the text > file will grow quite a bit. > > I came accross somebody else's suggestion of: > > text = None > for line in fileinput.input(): > if random.randrange(fileinput.lineno()) ==0: > text = line > > But couldn't that complete without selecting a line?
No. On the first line fileinput.lineno() will return 1, and random.randrange(1) will always return 0, so text will be set to the first line. Note that empty files are considered to be a single empty line, so you don't need to worry about files with zero lines. That's a clever way of making you not have to page in the entire file, although it still makes you scan the entire thing. -Bram _______________________________________________ Bits mailing list [EMAIL PROTECTED] http://www.sugoi.org/mailman/listinfo/bits
