0

I have multiple codes written in different cells in jupyter notebook. The first cell contains the file name on which I need to perform the task. I am facing difficulty in running loop in jupyter notebook as I want to perform operation file by file. i.e. first take file1 to go through all the cells and then come back to lookout for file2 and so on.

I know a similar question has been asked Link1 but I am not sure how it can be done in jupter as I know in spyder we can indent in for loop and it'll run till we complete all the task then it jumps to another one but here in jupyter it seems difficult as it's cell by cell operation.

Cell 1 file_names = ['file1','file2','file3']
Cell 2 a = []
Cell 3 for file in file_names:
           a.append(file)
  • 1
    Can't you execute all the cells one by one? Or even better - put all the codes in one cell? I don't think I understand what the problem is – alex Feb 23 '22 at 11:47
  • I can execute cell by cell but that's not what I am looking for. I want to run at one go just like we do in spyder but the problem with Jupyter is cell by cell operation where it doesn't know which file to work on by default when we run at one it takes the last file and run through. – Abhay Dodiya Feb 23 '22 at 13:00
  • 1
    That's how Jupyter works. Just put it all in one cell and run. – alex Feb 23 '22 at 13:11
  • Does this answer your question? [Run parts of a ipython notebook in a loop / with different input parameter](https://stackoverflow.com/questions/15635341/run-parts-of-a-ipython-notebook-in-a-loop-with-different-input-parameter) – E_net4 Aug 10 '22 at 11:15

1 Answers1

0

Your distribution of code to the cells is fine (i.e. it is one possibility out of many).

You define variables in cells 1 and 2 and execute the loop in cell 3. Your file processing takes place only in cell 3.

Of course, every cell must contain valid python syntax (as must a script opened in spyder). This means the body of the for-loop must be correctly indented.

cknoll
  • 2,130
  • 4
  • 18
  • 34
  • So, I can do it in Spyder whereafter for loop remaining piece of codes in indented inside for-- loop. I don't understand how to do the same in Jupyter as it's cell by cell operation if I run at one go it'll pick up only the last file in the loop. – Abhay Dodiya Feb 23 '22 at 13:02
  • If you run all cells in the correct order (1 → 2 → 3), then there is basically no difference between a script (run from spyder) and a notebook. Of course you must put the complete loop inside one cell. Do not mixup *cells* and *lines*. One cell can contain as many lines as you want. If it still does not work, please edit you questions and add error messages and/or screenshots. – cknoll Feb 23 '22 at 13:37