如何让Python将素数打印到文本文件中?

这个问题在这里已经有了答案:

  • 你如何追加到一个文件? 8个答案

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

    也许你想要

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

    真的,你不应该这样做,你应该用它来安全地打开你的文件,并且只在循环之外进行一次

    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)
    
    链接地址: http://www.djcxy.com/p/42411.html

    上一篇: How to get Python to print primes into a text file?

    下一篇: ping using python and save to a file