Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit206aec5

Browse files
committed
Python Context Managers code snippets
1 parentfab06d0 commit206aec5

File tree

9 files changed

+61
-0
lines changed

9 files changed

+61
-0
lines changed

‎Python-Context-Managers/Sample-Dir-One/mydoc.txt

Whitespace-only changes.

‎Python-Context-Managers/Sample-Dir-One/todo.txt

Whitespace-only changes.

‎Python-Context-Managers/Sample-Dir-One/work.txt

Whitespace-only changes.

‎Python-Context-Managers/Sample-Dir-Two/demo.txt

Whitespace-only changes.

‎Python-Context-Managers/Sample-Dir-Two/sample.txt

Whitespace-only changes.

‎Python-Context-Managers/Sample-Dir-Two/test.txt

Whitespace-only changes.

‎Python-Context-Managers/cm_demo.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
importos
2+
fromcontextlibimportcontextmanager
3+
4+
5+
@contextmanager
6+
defchange_dir(destination):
7+
try:
8+
cwd=os.getcwd()
9+
os.chdir(destination)
10+
yield
11+
finally:
12+
os.chdir(cwd)
13+
14+
15+
withchange_dir('Sample-Dir-One'):
16+
print(os.listdir())
17+
18+
withchange_dir('Sample-Dir-Two'):
19+
print(os.listdir())

‎Python-Context-Managers/sample.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Lorem ipsum dolor sit amet, consectetur adipiscing elit.

‎Python-Context-Managers/snippets.txt

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
class Open_File():
3+
4+
def __init__(self, destination):
5+
pass
6+
7+
def __enter__(self):
8+
pass
9+
10+
def __exit__(self, exc_type, exc_val, traceback):
11+
pass
12+
13+
14+
#### Using contextlib ####
15+
16+
@contextmanager
17+
def open_file(file, mode):
18+
f = open(file, mode)
19+
yield f
20+
f.close()
21+
22+
23+
with open_file('sample.txt', 'w') as f:
24+
f.write('Lorem ipsum dolor sit amet, consectetur adipiscing elit.')
25+
26+
print(f.closed)
27+
28+
29+
#### CD Example ####
30+
31+
cwd = os.getcwd()
32+
os.chdir('Sample-Dir-One')
33+
print(os.listdir())
34+
os.chdir(cwd)
35+
36+
cwd = os.getcwd()
37+
os.chdir('Sample-Dir-Two')
38+
print(os.listdir())
39+
os.chdir(cwd)
40+
41+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp