Reputation: 293
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?
Upvotes: 3
Views: 13003
Reputation: 61683
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.
Upvotes: 10
Reputation: 82924
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.
Upvotes: 5
Reputation: 3838
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)
Upvotes: 2
Reputation: 133557
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
..
Upvotes: 2