AttributeError: __enter__ ; context manager inside function

AttributeError: __enter__ ; context manager inside function

def get_reply(file_name, input): 
    import csv
    #error line
    with open(file_name, "r") as csv_f, csv.reader(csv_f, delimiter = ",") as csv_reader:  
        return search(csv_reader, input)

错误:

in get_reply
     with open(file_name, "r") as csv_f, csv.reader(csv_f, delimiter = ",") as csv_reader:
   AttributeError: __enter__

为什么会出现这个错误,如何解决?在这种情况下,这个错误是什么意思?

非常感谢您的帮助,我对编程还很陌生..

我将附上其余代码,作为上下文,这意味着通过处理 csv 文件 [user_input,response].

来处理对用户输入的回复

代码是这样写的这样可以导入复用.

def search(csv_reader, input) :
    for line in csv_reader:
        if input == line[0]:
            return line[1]

def get_reply(file_name, input): 
    import csv
    with open(file_name, "r") as csv_f, csv.reader(csv_f, delimiter = ",") as csv_reader:
        return search(csv_reader, input)

        
#Test execution                      
list1 = get_reply("csv_dataset.txt", input("Enter Input : "))  

csv.reader 尚未实现 __enter____exit__ 方法。所以你不能将它用作上下文管理器(这是你对 with 所做的)。

这样使用:

def get_reply(file_name, input): 
    import csv
    with open(file_name, "r") as csv_f:
        csv_reader = csv.reader(csv_f, delimiter = ",")
        return search(csv_reader, input)

如果您想将其用作上下文管理器,您可以使用 contextlib.

构建自己的包装器
import csv
from contextlib import contextmanager


@contextmanager
def csv_reader(*args, **kwargs):
    yield csv.reader(*args, **kwargs)


with open(file_name, "r") as csv_f, csv_reader(csv_f, delimiter = ",") as reader:
    return search(reader, input)