Adam_G
Adam_G

Reputation: 7879

Access values outside with-block

Is there a way, in the code below, to access the variable utterances_dict outside of the with-block? The code below obviously returns the error: ValueError: I/O operation on closed file.

from csv import DictReader

utterances_dict = {}
utterance_file = 'toy_utterances.csv'

with open(utterance_file, 'r') as utt_f:
    utterances_dict = DictReader(utt_f)

for line in utterances_dict:
    print(line)

Upvotes: 1

Views: 131

Answers (2)

rioV8
rioV8

Reputation: 28663

DictReader returns a view of the csv file.

Convert the result to a list of dictionaries.

from csv import DictReader

utterances = []
utterance_file = 'toy_utterances.csv'

with open(utterance_file, 'r') as utt_f:
    utterances = [dict(row) for row in DictReader(utt_f) ]

for line in utterances:
    print(line)

Upvotes: 1

Aaron
Aaron

Reputation: 2073

I am not an expert on DictReader implementation, however their documentation leaves the implementation open to the reader itself parsing the file after construction. Meaning it may be possible that the underlying file has to remain open until you are done using it. In this case, it would be problematic to attempt to use the utterances_dict outside of the with block because the underlying file will be closed by then.

Even if the current implementation of DictReader does in fact parse the whole csv on construction, it doesn't mean their implementation won't change in the future.

Upvotes: 1

Related Questions