简体   繁体   English

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

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

I have a python script which print in a text file every prime. 我有一个Python脚本,每个素数都在文本文件中打印。 I would like my script to pickup the list where it left off so basically take the contents of the last line as a variable. 我希望我的脚本从上次中断的地方开始提取列表,因此基本上将最后一行的内容作为变量。

Here is my current script: 这是我当前的脚本:

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()

I would like the variable x to get as an input the last line of primes.txt There should be on that last line "[245747]" if the greatest prime number is 245747. 我希望变量x作为素数的最后一行输入。如果最大质数为245747,则该最后一行应为“ [245747]”。

How could I achieve that? 我该如何实现? Thanks! 谢谢!

You can do use readlines and get the last item of the list: 您可以使用阅读行并获取列表的最后一项:

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

I think this should work. 我认为这应该有效。 You can just get rid of the 2 "[" and "]" with split or something similar. 您可以使用split或类似方法摆脱2个“ [”和“]”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM