All Tutorials / JustinRatliff / Reading and Writing with Files

Reading and Writing with Files

Step 8. Reading Random Lines

There is another example script named "ReadRandomLine", go ahead and run that script. It will read a random line from your "myfile" text file.

One use I could see for this would be to use it to read a text file and pick a quote, greeting or joke at random. Lets create a random joke teller to see how we can us this:

1. Create a new text file in your c:\temp folder named "jokes"

2. Lets add some jokes, but they have to fit on one line. Here are a few I found online:

A recent study has found that women who carry a little extra weight live longer than the men who mention it.

I find it ironic that the colors red, white, and blue stand for freedom until they are flashing behind you.

Today a man knocked on my door and asked for a small donation towards the local swimming pool. I gave him a glass of water.

Add those to your joke text file and save it. You should end up with 3 lines of jokes with no spaces between the lines.

3. Now add a new Script control and name it "RandomJokes" and enter the following code and save the script:

Code:


# Reads random line from the specified file

$filename = "c:\temp\jokes.txt"

if (FileExists($filename) = false)
print("File does not exist")
Halt()
endif

$cnt = 1

$txt = FileReadLineRandom($filename)

print("Random Line: " + $txt)
Say($txt)



This will print the joke in the output of the script debug window as well as speak it from the computer speakers.