gpt4 book ai didi

python - 值错误 : I/O operation on closed (csv) file

转载 作者:太空宇宙 更新时间:2023-11-04 04:43:08 28 4
gpt4 key购买 nike

我收到这个错误:

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)

最佳答案

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

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

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]

关于python - 值错误 : I/O operation on closed (csv) file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50179311/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com