被给了一些代码(我使用Python 3.2),并不断得到下面的错误。Python - 字符串错误
import csv
import collections
import itertools
grid = collections.Counter()
with open("test1.csv", "r") as fp:
reader = csv.reader(fp)
for line in reader:
for pair in itertools.combinations(line, 2):
grid[pair] += 1
grid[pair[::-1]] += 1
actors = sorted(set(pair[0] for pair in grid))
with open("connection_grid.csv", "wb") as csvfile:
writer = csv.writer(fp)
writer.writerow([''] + actors)
for actor in actors:
line = [actor,] + [grid[actor, other] for other in actors]
writer.writerow(line)
但我得到这个错误。
Traceback (most recent call last): File "C:/Python32/test.py", line 21, in writer.writerow([''] + actors) ValueError: I/O operation on closed file.
您编辑了第二个'with'以使用'作为csvfile',但'writer'仍尝试引用'fp'。这是行不通的。 – DSM
'作家= csv.writer(fp)'在这行代替fp与csvfile –
伙计们,那些是答案,不是评论。 – yak