'How to fix “AttributeError: __enter__” when using csv.reader(open(..)..)?

I get the following error with my code:

Traceback (most recent call last):
File "C:\Users\XXX\Sentiment Analysis-vader.py", line 34, in <module>
    f.printer()

File "C:\Users\XXX\Sentiment Analysis-vader.py", line 18, in printer
    with csv.reader(open('analyse_' + str(bloombergcode) + '.csv', 'r'), delimiter= ",",quotechar='|') as q2:

AttributeError: __enter__

Process finished with exit code 1

I used the following code:

import csv
from nltk.sentiment.vader import SentimentIntensityAnalyzer

class VaderSentiment:
    def __init__(self, bloomcode):
        self.bloomcode = bloomcode

    def print_sentiment_scores(self, sentence):
        self.sentence = sentence
        analyser = SentimentIntensityAnalyzer()
        snt = analyser.polarity_scores(self.sentence)
        print("{:-<40} {}".format(self.sentence, str(snt)))

    def printer(self):
        bloombergcode = self.bloomcode
        with csv.reader(open('analyse_' + str(bloombergcode) + '.csv', 'r'), delimiter= ",",quotechar='|') as q2:
            for line in q2:
                for field in line:
                    print_sentiment_scores(field)

for code in ('AAPL', 'NFLX'):
    f = VaderSentiment(code)
    f.printer()
    time.sleep(1)

I already saw some other similar problems (Python Json with returns AttributeError: __enter__) but the solutions do not work on my problem.

Does anyone see the problem?



Solution 1:[1]

You're not using csv.reader correctly. It does not support being placed inside a with statement.

Try to do it the same way as in the usage example:

with open('analyse_' + str(bloombergcode) + '.csv', 'r') as csv_file:
    q2 = csv.reader(csv_file, delimiter=',', quotechar='|')
    for line in q2:
        # ..rest of your code..

Wrap open instead inside the with (because open supports it and is actually the recommended way of using it) then use csv.reader inside it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1