Search code examples
pythonfunctionfile-handlingattributeerrorcontextmanager

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)

Error :

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

Why is this error occurring and how to resolve it? What does this error mean in this context?

Thanks a lot for your help, I am fairly new to programming..

I will attach the rest of the code, for context, that is meant to process replies to user input by going over a csv file [user_input,response].

The code is written this way so that it can be imported and reused.

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 : "))  

Solution

  • csv.reader has not implemented the __enter__ and __exit__ methods. So you cannot use it as context manager (this is what you do with the with).

    Use it in this way:

    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)
    

    If you want to use it as context-manager you can build own wrapper with the 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)