3

I'm writing a program that looks through CSVs in a directory and appends the contents of each CSV to a list. Here's a snippet of the offending code:

import glob
import re 

c = glob.glob("*.csv")
print c
archive = []

for element in c:
    look = open(element, "r").read()
    open = re.split("\n+", look)

    for n in open:
        n = re.split(",", n)[0]
        archive.append(n)

However, when I run this script, I get a TypeError: 'list' object is not callable. Can somebody please explain what's going on?

4 Answers 4

10

I think it's because you redefine open as a list and call it in the next loop iteration. Just give the list another name.

Note that strings have a split() method for when you don't need a regex.

Sign up to request clarification or add additional context in comments.

Comments

5

The fact that open is a builtin function is irrelevant. It could have been a function defined in the same module.

The basic problem is that the same name was used to refer to two different objects (a function and a list), both of which were needed again. When the first object was needed again, the name referred to the second object. Result: splat. The golden rule is: don't re-use names unthinkingly.

Comments

2

The gold rule is: never use the name of a builtin thing for your variables!

It's a matter of aliasing, just don't call the list open..

Comments

2

Agree with previous answers: never call a variable open or any other builtin.

You may be interested int the Python csv module, which will correctly parse csv files that re.split(',', line) won't.

Also, you can use the file object as a line-by-line iterator like so:

for line in open('data.csv'):
    do_something(line)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.