使用 .txt 文件行的内容作为 python3 变量的输入

Use content of .txt file line as input for python3 variable

我有一个 python 脚本,它在每个素数时打印在一个文本文件中。 我希望我的脚本从它停止的地方获取列表,所以基本上将最后一行的内容作为变量。

这是我当前的脚本:

def calc():
    while True:
        x = 245747
        y = (100**100)**100
        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', 'a+')
                print(n)
                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()

我希望变量 x 得到 primes.txt 的最后一行作为输入 如果最大素数是 245747,最后一行应该有“[245747]”。

我怎样才能做到这一点?谢谢!

您可以使用 readlines 并获取列表的最后一项:

file = open("primes.txt", "r").readlines()
x = file[len(file)-1]

我认为这应该可行。 您可以使用 split 或类似的东西去掉 2 个“[”和“]”。