Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用.txt文件行的内容作为python3变量的输入_Python_Python 3.x_Text_Primes - Fatal编程技术网

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

使用.txt文件行的内容作为python3变量的输入,python,python-3.x,text,primes,Python,Python 3.x,Text,Primes,我有一个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=

我有一个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“[”和“]”。

唯一的问题是:“[”和“]”在文本文件中作为数字的括号。列表的最后一项被认为是str而不是int。
文件[len(file)-1]
可以更清楚地写成
文件[-1]