Skip to content

Instantly share code, notes, and snippets.

@ReSTARTR
Created February 6, 2011 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ReSTARTR/813385 to your computer and use it in GitHub Desktop.
Save ReSTARTR/813385 to your computer and use it in GitHub Desktop.
'with'文を使ったファイルオープン(かつ自動クローズ)
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 )
}
}
with file('foo.txt') as line:
for l in line :
print(l)
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()
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