Created
April 12, 2025 18:12
-
-
Save bigntallmike/264ac99821f54e7fe478dd895277c1d4 to your computer and use it in GitHub Desktop.
Old vs new file reading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# | |
# We want to open the file specified and read the data out of it. | |
import sys | |
def old_way(filename): | |
fd = open(filename) | |
if not fd: | |
print("error of some kind") | |
sys.exit(1) | |
# If we were also writing to the file we might throw an exception and need to handle that | |
return fd.read() | |
def new_way(filename): | |
# This is a context manager | |
with open(filename) as fd: | |
return fd.read() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment