Jupyter Anaconda: load text file into python

73,853

Solution 1

in Anaconda Python with Jupyter NoteBook you have to give the absolute path with \\ just like given below

import pandas as pd
df = pd.read_csv("D:\\Nu\\2SEMESTER\\Data Science\\Assignments\\Assignment-1 data\\file.txt")
df     # with this command you can see your file

Solution 2

from pathlib import Path

#file = Path.joinpath('Resources', 'test.txt')
file = Path.cwd() / 'Resources/test.txt'
#file.read_text()

    # Open the file in "read" mode ('r') 
with open(file, 'r') as text:
    textfile = text.read()
    print(textfile)

Import the module pathlib. More information can be found at https://realpython.com/python-pathlib/

Share:
73,853
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I have Anaconda Python and Jupyter running on Mac. After typing the following code:

    import numpy as np
    import matplotlib.pyplot as plt
    iris = np.genfromtxt("data/iris.txt",delimiter=None) 
    

    I get the error: IOError: data/iris.txt not found. I have tried putting the iris file in the anaconda folder: Users/anaconda/lib/python2.7

  • Admin
    Admin over 7 years
    but the error says:Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/ashwinc/anaconda/lib/python2.7/site-packages/numpy/l‌​ib/npyio.py", line 1451, in genfromtxt Doesn't that mean that it is searching in the anaconda folder?
  • Jamie Phan
    Jamie Phan over 7 years
    That's the Traceback. It is going through each step of the program that 'failed', specifying which exact function call raised an error. In this case npyio.py. The funcction npyio.py has raised the error IOError: data/iris.txt not found. . Or in other words, the Traceback is simply telling you some function is trying to tell you some error.
  • Admin
    Admin over 7 years
    Ok. So i used your import os code snippet. In the base_path, I put the directory to a folder in my desktop which has the iris data. Then I copied the rest of your code as you wrote it. I then re ran the import numpy as np import matplotlib.pyplot as plt iris = np.genfromtxt("data/iris.txt",delimiter=None). I still get the same error
  • Jamie Phan
    Jamie Phan over 7 years
    Well no, the above code is an example of how you can use absolute paths. Simply put, the path specified as the first argument in the function call np.genfromtext(...) must lead to the file from where you are calling Python if it is a relative path.
  • user391339
    user391339 almost 7 years
    was the op referring to a jupyter notebook?