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

时间:2016-10-21 17:43:16

标签: python

我编写了一个Python工具,用于计算给定范围内的素数。然后我决定从shell中复制数字,创建一个txt文件,每次粘贴它们都有点麻烦,如果我能让工具将素数插入到文本文件中,那将非常方便。

我试过了:

def calc():
    while True:
        x = int(input("Please specify the lower end of the range...."))
        y = int(input("Please specify the upper end of the range...."))
        for n in range (x,y):
            if all(n%i!=0 for i in range (2,n)):
                a=[]
                a.append(n)
                fo = open('primes.txt', 'w')
                print (">>>Writing the values to primes.txt...")
                print ("##########Calculated by my prime calculator##########", file = fo)
                print ("", file = fo)
                print ((a), file = fo)
                fo.close
        s = input('To do another calculation input yes, to quit input anything else...')
        if s == 'yes':
            continue    
        else:
            break
calc()

编辑:

使用open(“primes.txt”,“a”)作为解决问题的方法

但是,我无法让Python将n值保存到内存中并将它们附加到不断增长的列表中。

你们真棒。关于Python愚蠢的部分是一个幽默的尝试lol。

1 个答案:

答案 0 :(得分:3)

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)