Created
February 6, 2011 14:15
-
-
Save ReSTARTR/813385 to your computer and use it in GitHub Desktop.
'with'文を使ったファイルオープン(かつ自動クローズ)
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
def swith(fileName: String)(f: Iterator[String]=>Unit) { | |
val in = new FileInputStream(fileName) | |
try { | |
f(Source.fromInputStream(in).getLines) | |
} finally { | |
in.close | |
} | |
} | |
// 使用例 | |
swith("foo.txt") { lines => | |
for (line <- lines) { | |
println( line ) | |
} | |
} |
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
with file('foo.txt') as line: | |
for l in line : | |
print(l) |
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
from contextlib import closing | |
with closing(file('foo.txt')) as page: | |
for line in page: | |
print line | |
# closingはこれと同等 | |
from contextlib import contextmanager | |
@contextmanager | |
def closing(file): | |
try: | |
yield file | |
finally: | |
thing.close() |
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
class Reader(object): | |
def __init__(self, fname): | |
self.fname = fname | |
def __enter__(self): | |
self.file = file(self.fname) | |
return self.file | |
def __exit__(self, exp_type, exp_value, exp_traceback): | |
self.file.close() | |
# 使用例 | |
with Reader('foo.txt') as lines: | |
for line in lines: | |
print(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment