How to get Python to print primes into a text file? [duplicate]

fo = open('primes.txt', 'w') #tells python to open the file and delete everything in it

perhaps you want

fo = open('primes.txt', 'a') # tells python to append to the file

really you should not be doing this at all you should use with to safely open your file and do it once only outside of the loop

with open("primes.txt","w") as fo:
    for n in range (x,y):
        if all(n%i!=0 for i in range (2,n)):
            a=[]
            a.append(n)             
            print (">>>Writing the values to primes.txt...")
            print ("##########Calculated by my prime calculator##########", file = fo)
            print ("", file = fo)
            print ((a), file = fo)

Browse More Popular Posts

Leave a Comment