forked from CoreyMSchafer/code_snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Python Context Managers code snippets
- Loading branch information
1 parent
fab06d0
commit 206aec5
Showing
9 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import os | ||
from contextlib import contextmanager | ||
|
||
|
||
@contextmanager | ||
def change_dir(destination): | ||
try: | ||
cwd = os.getcwd() | ||
os.chdir(destination) | ||
yield | ||
finally: | ||
os.chdir(cwd) | ||
|
||
|
||
with change_dir('Sample-Dir-One'): | ||
print(os.listdir()) | ||
|
||
with change_dir('Sample-Dir-Two'): | ||
print(os.listdir()) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
|
||
class Open_File(): | ||
|
||
def __init__(self, destination): | ||
pass | ||
|
||
def __enter__(self): | ||
pass | ||
|
||
def __exit__(self, exc_type, exc_val, traceback): | ||
pass | ||
|
||
|
||
#### Using contextlib #### | ||
|
||
@contextmanager | ||
def open_file(file, mode): | ||
f = open(file, mode) | ||
yield f | ||
f.close() | ||
|
||
|
||
with open_file('sample.txt', 'w') as f: | ||
f.write('Lorem ipsum dolor sit amet, consectetur adipiscing elit.') | ||
|
||
print(f.closed) | ||
|
||
|
||
#### CD Example #### | ||
|
||
cwd = os.getcwd() | ||
os.chdir('Sample-Dir-One') | ||
print(os.listdir()) | ||
os.chdir(cwd) | ||
|
||
cwd = os.getcwd() | ||
os.chdir('Sample-Dir-Two') | ||
print(os.listdir()) | ||
os.chdir(cwd) | ||
|
||
|