使用.txt文件行的内容作为python3变量的输入
我有一个python脚本,每个素数都打印在一个文本文件中。 我想让我的脚本从它停止的地方提取列表,所以基本上把最后一行的内容作为变量 以下是我当前的脚本:使用.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=
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]