开发者

Python "List" object is not callable

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?


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.


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.


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..


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜