Read visitor data from a csv file

new to python. i need to read visitor data from a csv file, how can I adjust this code so it wont give errors anymore?

import csv

with open(‘m.csv’) as csvfile:
file = csv.reader(csvfile, delimiter=‘,’)

linecount = 0
for line in file:
if linecount == 0:
print(‘names of the columns:’, ', '.join(line))
print(‘date of visits:’, ‘’.join(line[1]),
',visited websites: ', ‘’.join(line[2]))

First fix your delimiters. There are quotes there that do not delimit strings in Python. Are you using a word processing program to edit it? Use a program editor to prevent this.

I do not know what other errors you encounter, fed with a csv having three “columns”, it is working, after fixing the delimiters.

~/python/test1> python -m clientsnames
names of the columns: Field1 field2  field3
date of visits: A value2 ,visited websites:   "A value3"

Please read the pinned thread in order to understand how to post code with proper formatting, so that we can see the code as you actually have it. Especially in Python it is not possible to look for problems properly, unless the code is properly formatted.

Please also show whatever error message you get, by copying and pasting, starting from the line that says Traceback (most recent call last):, all the way to the end, and formatting it the same way as the code. This way we can understand what problem was reported to you. It’s not always possible to guess what is wrong just by looking at the code, because it could also depend on what is in your CSV file - or, indeed, whether you have the CSV file that you’re expecting to have, in the place that Python is looking for it.

errormessage: IndexError: list index out of range

the code has been slightly altered, as it is a data.txt file that needs to be read. not using word, but py charm to code. this part of the code I am confused about, what exactly does it mean:

import csv

with open(‘data.txt’) as csvfile:
file = csv.reader(csvfile, delimiter=‘,’)

What you have here, is context file handler manager, reading a csv file and should be formatted like this:

import csv

with open("data.csv", mode="r", encoding="UTF-8") as data:
    reader = csv.reader(data)
    for data_row in reader:

You’ll notice a couple things here:

  1. I’ve used the file name data.csv, because, well, it’s a ‘csv’ file, not a ‘text’ file[1].

  2. You don’t need the delimiter option, because again, it’s a ‘csv’ file.

  3. I have included the options that you really should include, as ‘best practice’.

  4. It’s correctly indented.

An IndexError is very specific and it should be quite easy to debug.

  1. Remember to change the file extension to .csv ↩︎