Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving the output of a cell in jupyter notebook with a new line after each number

I saved output of a cell as a txt file as follows:

First cell:

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

Second cell:

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

Below is a small piece of code that I wanted to save:

#%%
np.seterr(over='ignore')

a = np.uint32(1664525)
c = np.uint32(1013904223)
seed = np.uint32(1)

rng = LCG(seed, a, c)
q = [rng.next() for _ in range(0, 2500000)]

The file is saved, however the generated numbers are separated by a comma, but I want each generated number to be separated by a new line, not a comma

I tried to change "w" to "a" and add "\ n" as below but it does not work for me.

with open('output.txt', 'a') as f:
    f.write("\n")
like image 767
tbone Avatar asked Sep 05 '25 20:09

tbone


1 Answers

%%capture capture all the out of the code beside it in this cell, so you can print out all the elements from the list.

%%capture cap --no-stderr
for i in q:
    print(i)

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

cap.stdout handle what %%capture captured as a whole, so when you tried to add \n, it won't work.

Is it what you want?

like image 56
ComplicatedPhenomenon Avatar answered Sep 09 '25 01:09

ComplicatedPhenomenon