Serdia
Serdia

Reputation: 4428

how to load csv data in Python 3 using Jupyter

I am trying to import data from a csv file using Jupyter. I am new to Python. It works fine in IDLE, but not in Jupyter.

import csv
with open("mpg.txt","r") as mpgFile:
    mpgFileReader = csv.reader(mpgFile)
    mpgList = []
    for row in mpgFileReader:
        if len (row)!=0:
            mpgList = mpgList + [row]
mpgFile.close()
print(mpgList)

This is the error I receive

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-60-42823a11b1d0> in <module>()
      1 import csv
----> 2 with open("mpg.txt","r") as mpgFile:
      3     mpgFileReader = csv.reader(mpgFile)
      4     mpgList = []
      5     for row in mpgFileReader:

FileNotFoundError: [Errno 2] No such file or directory: 'mpg.txt'

I also tried to specify the full path of the file:

"C:\Users\serdi\Documents\Test\mpg.txt"

But then it gives me another error:

  File "<ipython-input-61-fed3bca4876a>", line 2
    with open("C:\Users\serdi\Documents\Test\mpg.txt","r") as mpgFile:
             ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Upvotes: 1

Views: 2204

Answers (2)

john2195
john2195

Reputation: 1

I used ("C:\Users\JOHN-PC\Videos\ml-twitter-sentiment-analysis-develop\data\twitter_train.csv") for load twitter data set. I always got problem in python 3 .

Upvotes: 0

Stephen Rauch
Stephen Rauch

Reputation: 49812

The original problem is likely as you surmised, namely the path is incorrect. However the second error is due to the \ in the "C:\Users\serdi\Documents\Test\mpg.txt" The \ is an escape. There are at least three alternatives.

Use a raw string:

with open(r"C:\Users\serdi\Documents\Test\mpg.txt","r") as mpgFile:

note the r in front of the string.

Escape the \:

with open("C:\\Users\\serdi\\Documents\\Test\\mpg.txt","r") as mpgFile:

Use '/' instead of \:

with open("C:/Users/serdi/Documents/Test/mpg.txt","r") as mpgFile:

Upvotes: 2

Related Questions