Reputation: 37
I am trying to import a csv file from my desktop to my jupyter notebook and then open and read it. I made sure to save the csv file in the same folder as the ipynb file.
here is the code I've used so far:
%matplotlib inline
import csv
import matplotlib.pyplot as plt
import os
userhome = os.path.expanduser('~')
csvfile= userhome + r'/Desktop/Software/evil_corp.csv'
open(csvfile, "r")
and this is the response I'm getting:
<_io.TextIOWrapper name='/Users/jessicanicholson/Desktop/Software/evil_corp.csv' mode='r' encoding='UTF-8'>
how do i proceed from here? I thought the last request would open/ view the file.
Upvotes: 1
Views: 9988
Reputation: 151
Your code returns the file descriptor, to view the csv file you have to open the file as you did but with a "with" statement like this:
with open(csvfile,'r')as f:
data = csv.reader(f)
for row in data:
print(row)
Upvotes: 1
Reputation: 837
Just open the file using csv.reader
, and start reading into it.
>>> f = open(csvfile, "r")
>>> data = csv.reader(f)
>>> data
<_csv.reader object at 0x7f5a04e65208>
>>> for row in data:
print(row)
If you are dealing in with CSV data, you can also use Pandas to make your life really easy. Here is an example:
>>> import pandas as pd
>>> df = pd.read_csv(csvfile)
>>> df.head()
Upvotes: 0