Saving the output of a cell as a txt file in jupyter notebook

Solution 1:

Run below in another cell

%%capture cap --no-stderr
print(q)

Then again another cell

with open('output.txt', 'w') as f:
    f.write(cap.stdout)