Related to https://app.dataquest.io/m/452/reading-and-writing-to-files/6/encoding-identification-workflow
I was wondering how come following code executes, shouldn’t variable “encoding_name” go out of scope when the first context manager exits, how come the second context manager can still access it?
import csv
import chardet
with open('kyoto_restaurants.csv', mode='rb') as file:
raw_bytes = file.read(32)
encoding_name = chardet.detect(raw_bytes)['encoding']
print(encoding_name)
with open('kyoto_restaurants.csv', encoding=encoding_name) as file:
rows = list(csv.reader(file))