[Tutor] Simple Question...

Max Noel maxnoel_fr at yahoo.fr
Sat Oct 16 20:09:27 CEST 2004

On Oct 16, 2004, at 18:46, Ali Polatel wrote:

> Hi dear tutors...
> I want to write a programme that will get certain information from a 
> file.:
> open('c:\\example.txt','a')  # file opened...
> Now I want it to choose a random line and read it... but just one line 
> and not the first one but a random one...
> how to do that?
> Regards,
> Ali Polatel

	There's probably a way to do it exactly how you described it. However, 
it'd be too complicated and not a lot faster than what I'm going to 

	Anyway. The fast and easy way to do that is to load the entire file in 
an array using readlines(), then rand a line and access it.

import random

def randomLineFromFile(fileName):
	source = open(fileName, 'r')
	lines = source.readlines()	# an array of all the file's lines
	return lines[random.randint(1, len(lines))]

	This will work perfectly if your file is small enough to fit in your 
computer's memory. If you want a function that does this on large 
files, you'll have to use something in those lines:

import random

def randomLineFromBigFile(fileName, numLines):
	whatLine = random.randint(1, numLines)	# choose a random line number
	source = open(fileName, 'r')
	i = 0
	for line in source:
		i += 1
		if i == whatLine: return line
	return None

	This function uses very little (and a constant amount of) memory. The 
downside is that you have to know the total number of lines in the file 
(that's the numLines argument) before calling it. It's not a very hard 
thing to do.

(Oh, by the way, it's a bad practice to use backslashes in file paths. 
If you use them, your program will only work on Windows, and it 
requires typing an additional character each time -- use slashes, they 
work everywhere and will make the transition easier when you eventually 
see the light :p )

-- Wild_Cat
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

More information about the Tutor mailing list