Home > Net >  Python3 calling csv.DictReader - object is not callable
Python3 calling csv.DictReader - object is not callable

Time:03-24

I am new to Python, and writing a simple code to categorise my daily expenses. The program reads csv files with transactions, performs some math, and then prints out the results. Thanks in advance for your support.

Problem: when calling csv.DictReader for the second time in code gives an error.

Error: line 12, in csv.reader = csv.DictReader(csvfile, delimiter = ';') File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/csv.py", line 86, in init self.reader = reader(f, dialect, *args, **kwds) TypeError: 'DictReader' object is not callable

import csv

ledgerDebit = []
ledgerCredit = []

with open('jan2022_full.csv', 'r') as csvfile:
    csv.reader = csv.DictReader(csvfile, delimiter = ';')
    for row in csv.reader:
        ledgerDebit.append(row)

with open('jan2022credit_full.csv', 'r') as csvfile:
    csv.reader = csv.DictReader(csvfile, delimiter = ';')
    for row in csv.reader:
        ledgerCredit.append(row)

CodePudding user response:

instead of

csv.reader = csv.DictReader(csvfile, delimiter = ';')

use

import csv

ledgerDebit = []
ledgerCredit = []

with open('jan2022_full.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile, delimiter = ';')
    for row in reader:
        ledgerDebit.append(row)

with open('jan2022credit_full.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile, delimiter = ';')
    for row in reader:
        ledgerCredit.append(row)

reader is just a variable of the class reader, if you use csv.reader = ... you are essientially trying to overwrite a class definition within the csv module

https://docs.python.org/3/library/csv.html#csv.DictReader

  • Related