1

So I found this crappy old laptop (my now moved out sister's from about '05) in my basement and I've been messing around with it by running huge calculations on it in Python and leaving it for hours. My newest project is saving the first 1 billion primes to a text file (pointless, I know, but somewhat interesting) So heres my code so far:

from time import time
start_time = time()
f = open('primes.txt', 'w')
counter = 1
number = 1
while counter <= 1000000000:
    if prime(number): #NOTE: prime is a function checking if a number is prime
        f.write(str(counter) + '   ' + str(number) + '\n')
        counter += 1
    number += 1

f.write(time() - start_time)
f.write('This file contains the first %s primes.' % (counter)) 

f.close

The issue I have is at the end. I want the time and prime to be listed on the first line of the file, not the end, because a billion primes is a very long text file. Obviously I can't write it before the primes are calculated / written, because the time and prime will both be 0.

Is there any way to, after the calculation and writing is done, to insert the info to the start (first line) of the file?

SOLVED! Adding whitespace at the start and then using f.seek(0) worked perfectly. As for the program, the first 100 million took around 3 days! Clearly not the most efficient program, but it is also only running on 1 core which is only 800 MHz

davenz
  • 399
  • 2
  • 3
  • 9
  • yes put you'd have to write the entire file again, why not have an other file with results in. – Tony Hopkinson Dec 17 '12 at 12:07
  • 4
    not necessary, you could keep enough space in the beginning of the file and then simply overwrite it. – devsnd Dec 17 '12 at 12:10
  • Possible duplicate of http://stackoverflow.com/questions/4454298/prepend-a-line-to-an-existing-file-in-python – Tuim Dec 17 '12 at 12:11

1 Answers1

3

you can write some whitespace at the beginning of the file

f.write(" "*30)

and then, when you finished calculating, you go back to the beginning and overwrite this white space:

f.seek(0)
f.write(str(counter)+" primes")
devsnd
  • 7,382
  • 3
  • 42
  • 50