with
statement creates what’s called a context: when the with
block ends, Python will automatically close the file, even if an exception is raised inside the with
block. You’ll learn more about with
blocks and file objects in the Files chapter.with open('plural4-rules.txt', encoding='utf-8') as pattern_file:
for line in pattern_file:
pattern, search, replace = line.split(None, 3)
rules.append(build_match_and_apply_functions(
pattern, search, replace))
with 類似於 C#裡的using用法
會自動關閉 open()