Python Forum

Full Version: Error while loading the csv file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi , While I am trying to load csv file using the below code :
***********************************************************
# Load a CSV file
def load_csv(filename):
file = open(filename, "rb")
lines = reader(file)
dataset = list(lines)
return dataset

# load and prepare data
filename = 'D:/python/Training/Decision Tree/data.csv'
dataset = load_csv(filename)
***********************************************************
Error Traceback (most recent call last)
<ipython-input-7-798d54f914f1> in <module>()
11 # load and prepare data
12 filename = 'data_banknote_authentication.csv'
---> 13 dataset = load_csv(filename)
14
15

<ipython-input-7-798d54f914f1> in load_csv(filename)
6 file = open(filename, "rb")
7 lines = reader(file)
----> 8 dataset = list(lines)
9 return dataset
10

Error: iterator should return strings, not bytes (did you open the file in text mode?)

Can anyone please suggest , why this is happening ?
You are opening the file in binary mode - ' rb '. Open it just for reading - file = open(filename, "r")
The csv module is iterating over the file object. It relies on the fact, that a iterating over a file, which has been opened in text mode, yields one line per iteration step.

Open the file implicit in text mode with open(filename, "r") or open(filename) or do it explicit with open(filename, "rt")

Further information about open and it's modes: https://docs.python.org/3.6/library/functions.html#open
Thanks to all for helping me out . It worked .