In this Python code below that I am working on, I am having a problem with file I/O. Specifically: I need help finding how many lines there are in an opened file, and how to go to a specific line number in a file.
Here is what I have so far:
import random import time wordlist = open('Wordlist.txt', 'r') counter = 0 for line in wordlist: counter += 1 wordlist.close() wordlist = open('Wordlist.txt', 'r') randomline = random.randint(1, counter) randomword = wordlist.readline(randomline) data = open('DATA.txt', 'w') data.write(randomword) data.close() wordlist.close()
Basically: the file Wordlist.txt is a list of words, each entered on a separate line, and the file DATA.txt is an empty file. My goal with this program is to:
1) Count how many lines there are in the file Wordlist.txt
2) With that info, generate a random number between 1 and the amount of lines there are in the file
3) Find the line number equal to the random number generated
4) Take that line, and write it to DATA.txt
The I figured out how to count the number of lines, but as you can see, it is messy and I was wondering if there is a better way to do it that does not involve opening and closing then opening the file again.
But mainly, I need something like
Readline([[i]size[/i]])but where you could enter a line number instead of a size in the parens.
Any help given would be extremely...helpful....