Try this, should give you an idea
stack = []
lines=''
textfile = open("jkl.txt","w")
while lines!='stop':
lines = input("Enter lines of input: ")
if lines == 'stop':
while len(stack) > 0:
outString = stack.pop() + '\n'
textfile.write('outString')
print(outString)
else:
stack.append(lines)