Skip to main content
 首页 » 编程设计

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

2024年12月31日13thcjp

我收到这个错误:

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]