wuwucat
wuwucat

Reputation: 2621

how to upload a text file into ipython notebook

I want a whole file as a text file instead of just a cell in IPython notebook.

I write some codes in IPython notebook and now I want to test them ,so I tried to upload some text file into IPython notebook as the raw data.But the files' extension are always ".ipynb" and the format of the text files have changed so my code can't read it correctly.

How could I upload a text file into Ipython notebook? thanks in advance

Upvotes: 2

Views: 14363

Answers (4)

Bill
Bill

Reputation: 11603

There is a magic function to load the contents of a text file into the current cell.

%load full/path/to/my_file.txt

But it only load the file once, after which the command is commented-out so it doesn't execute every time you run the notebook.

Upvotes: 0

yoonghm
yoonghm

Reputation: 4625

It may be late, you can do this

%%pycat full/path/to/text/file

Upvotes: 2

Homa F.
Homa F.

Reputation: 41

The following lines open a text file and display the content in a jupyter notebook cell.

text_file = open(full/path/to/text/file)
file_content = text_file.read()
print(file_content)
text_file.close()

I hope this helps.

Upvotes: 3

nom-mon-ir
nom-mon-ir

Reputation: 3918

Can you be more elaborate?

Are you trying to read data out of the text file? In that case regular python open and read functions can get you the data into variables. You can even do Unix "cat" the contents of the file in a variable:

        var=!cat file

Or are you trying to get the text in the ipynb files as content in an input cell so you can edit them and run them? The ipynb files are usually created by the notebook engine and they are JSON formatted. So if you just copy paste the text from them into a cell, they won't be usable as is. Use some JSON parsing to interpret their content. They are not regular python code so "%run file" wont work to get their code executed by ipython.

Elaborating the use cases may help others to give solutions...

Upvotes: 4

Related Questions