Importing .txt file without numpy and Pandas

I’m new to Python and my question is Why we can’t directly import Text files in Jupyter Notebook without importing numpy and pandas.?

I had previously worked in Python idle where I can easily read any text file using open() function but in Jupyter notebook, this function isn’t working.

open() still works in Jupyter notebooks. Go to here and click on launch binder. The session that spins up lacks pandas and the following code pasted in a notebook still works to make a text file, named demofile.txt, and then read it in using open().

s='''This is a test
This is still a test
Really this is a test
'''
%store s >demofile.txt
h = open("demofile.txt", "r")
for line in h:
    print (line)
h.close()
2 Likes

I got it but what if we have Text file sitting in any directory? then how we’d acces it?

A couple of ways exist.
One particular to Jupyter is to use the %cd magic to change the current working directory. Note that it is different than !cd. And in fact often the magic command on cd is added automatically in most versions and interfaces, see about automagic here. (Your mileage may vary here and that is why I prefer to be explicit using %cd even when cd will suffice.)
So using you %cd you can direct the current working directory in your notebook to the new location and act like you are working inside there with open().

Alternatively, you can use the absolute path to the file or relative path to the file as part of the string where you specify the name for the file in your open() command. In the case of relative, it would be relative what it shows in your notebook at the time if you run a cell with %pwd as the content. %pwd is the magic command for print working directory, see here.

Below is demonstration of these concepts expanded from the first one I posted. It makes a new directory called othdir below whatever is the current working directory in your system and saves the text file in that new directory by switching to that as the working directory. Then the working is switched again back to the starting directory, above the new directory. From there the open() function is run and the relative path is included as part of the file path and name information provided to open() so that the text file is opened from within the new directory, even though at the time the working directory is the same as when all this began.

s='''This is a test
This is still a test
Really this is a test
'''
%mkdir othdir
%cd othdir
%store s >demofile.txt
%cd ..
h = open("othdir/demofile.txt", "r")
for line in h:
    print (line)
h.close()