Python ValueError:对已关闭(csv)文件执行I/O操作

Python ValueError:对已关闭(csv)文件执行I/O操作,python,python-3.x,Python,Python 3.x,我得到这个错误: 回溯(最近一次呼叫最后一次): 文件“so.py”,第7行,在 供x审查: ValueError:对关闭的文件执行I/O操作。 代码: 在Python3中,map()函数不完全处理输入对象,只返回一个迭代器。因此,直到您的for循环为每一行调用时,文件才真正得到处理。但是到那时,文件已经关闭,因为您的代码将与块一起离开 你有两个选择。首先,您可以让调用者传入打开的文件,并让他们处理打开和关闭文件的操作: def get_reviews(rev_file): retur

我得到这个错误:

回溯(最近一次呼叫最后一次):
文件“so.py”,第7行,在
供x审查:
ValueError:对关闭的文件执行I/O操作。
代码:

在Python3中,
map()
函数不完全处理输入对象,只返回一个迭代器。因此,直到您的
for
循环为每一行调用时,文件才真正得到处理。但是到那时,文件已经关闭,因为您的代码将
块一起离开

你有两个选择。首先,您可以让调用者传入打开的文件,并让他们处理打开和关闭文件的操作:

def get_reviews(rev_file):
    return map(lambda x: x.strip().split(','), rev_file)

with open(path) as file1:
    for review in get_reviews(file1):
        print(review)
或者让
get_reviews()
完全处理文件,比如返回列表

def get_reviews(path):
    with open(path, 'r', encoding = "utf-8") as file1:
        return list(map(lambda x: x.strip().split(','), file1))

# alternate version using a list comprehension instead of map()
def get_reviews(path):
    with open(path, 'r', encoding = "utf-8") as file1:
       return [x.strip().split(',') for x in file1]

您在文件对象上返回了一个生成器。当您在函数中使用块离开
时,该文件已关闭。

错误发生在哪一行?顺便说一句,您应该使用
csv.reader
读取csv文件,您的代码无法正确处理引用和转义。欢迎使用StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。
get_reviews()
返回的是一个生成器,它在x:
语句中的
for review之前不会执行,但该文件已关闭,因为
with
已关闭
文件1
。错误发生在第7行
def get_reviews(path):
    with open(path, 'r', encoding = "utf-8") as file1:
        return list(map(lambda x: x.strip().split(','), file1))

# alternate version using a list comprehension instead of map()
def get_reviews(path):
    with open(path, 'r', encoding = "utf-8") as file1:
       return [x.strip().split(',') for x in file1]
reviews = map(lambda x: x.strip().split(','), 
             [_ for _ in file1] )