【发布时间】:2018-05-05 01:31:57
【问题描述】:
我收到此错误:
Traceback (most recent call last):
File "so.py", line 7, in <module>
for review in x:
ValueError: I/O operation on closed file.
代码:
def get_reviews(path):
with open(path, 'r', encoding = "utf-8") as file1:
reviews = map(lambda x: x.strip().split(','), file1)
return reviews
x = get_reviews("reviews.csv")
for review in x:
print(review)
【问题讨论】:
-
错误发生在哪一行?
-
顺便说一句,您应该使用
csv.reader来读取 CSV 文件,您的代码无法正确处理引用和转义。 -
欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
-
get_reviews()返回的是一个生成器,直到for review in x:语句才会执行,但是到那时文件已经关闭,因为with已经关闭file1。 -
错误发生在第 7 行
标签: python python-3.x