Reputation: 13
I'm trying to open a CSV file on Python 3.7/Spyder/Anaconda IDE.
I want to learn how to import csv files either by using pandas and by using the csv libraries.
The following code worked well and a csvfile variable containing the data frame was created:
import pandas as pd
csvfile = pd.read_csv(r'C:\Users\Documents\PyLearning\data_file.csv', sep=',')
However I didn't get the same result with the csv module. After running the following code, nothing happend.
import csv
csvfile = open('data_file.csv', 'rb')
reader = csv.reader(csvfile)
I got no error message but no variable was created.
I would like to some help to understand why this is happening.
EDIT: It seems csv module was replaced by unicodecsv module at more recent python versions https://pypi.org/project/unicodecsv/
Upvotes: 1
Views: 383
Reputation: 515
The beauty of using pandas' read_csv is that it automatically and most importantly quickly converts said csv into a usable dataframe.
using csv.reader simply refers to the csv in question but you would have to call an iterator to get a result.
i.e.: (from https://docs.python.org/3/library/csv.html)
>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
Upvotes: 0
Reputation: 2693
If you're looking for how to use a builtin Python module (the csv
module, for example), I would recommend looking at the official Python documentation.
You can find the documentation for the csv module here.
Here's the first example they give of reading a csv file (see https://docs.python.org/3/library/csv.html#examples):
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
In the loop, you can access row
to store it in whatever data structure you prefer.
For example, to put it in all in a list:
with open('some.csv', newline='') as f:
reader = csv.reader(f)
data = [row for row in reader]
print(data)
Upvotes: 1