1

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)
4
  • 2
    why do you want to use it outside ? Just put your for loop in the with strcture ? Commented Aug 12, 2020 at 14:19
  • I understand how to do it in this case. But the actual program is more multi-faceted Commented Aug 12, 2020 at 14:21
  • 2
    Wouldn't this work?: define a function, use with in that function and then return what you want, work with returned data Commented Aug 12, 2020 at 14:29
  • 1
    @Ruli - That could work; I'll play around with that. Thanks. Commented Aug 12, 2020 at 14:38

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.