【问题标题】:Use content of .txt file line as input for python3 variable使用 .txt 文件行的内容作为 python3 变量的输入
【发布时间】:2017-02-19 00:50:07
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x text primes


    【解决方案1】:

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

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

    我认为这应该可行。 你可以用 split 或类似的方法去掉 2 个“[”和“]”。

    【讨论】:

    • 只有符号:“[”和“]”在文本文件中作为数字的括号。列表的最后一项被认为是 str 而不是 int...
    • file[len(file)-1] 可以更清楚地写成file[-1]
    猜你喜欢
    • 1970-01-01
    • 2018-05-23
    • 2019-03-12
    • 1970-01-01
    • 2013-01-28
    • 2017-06-09
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多