tempfileライブラリを使うと一時ファイルやディレクトリを作成できる。
TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)
file_name = ''
with tempfile.TemporaryFile() as f:
file_name = f.name
f.write(b'abcd')
f.seek(0)
print(f.read())
print(pathlib.Path(file_name).exists()) # => False
NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None)
path = None
with tempfile.NamedTemporaryFile() as f:
f.write(b'abcd')
f.seek(0)
print(f.read())
path = f.name
print(pathlib.Path(path).exists()) # => True
print(pathlib.Path(path).exists()) # => False
path = None
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(b'abcd')
f.seek(0)
print(f.read())
path = f.name
print(pathlib.Path(path).exists()) # => True
print(pathlib.Path(path).exists()) # => True
SpooledTemporaryFile(max_size=0, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)
path = None
with tempfile.SpooledTemporaryFile() as f:
f.write(b'abcd')
f.seek(0)
print(f.read())
TemporaryDirectory(suffix=None, prefix=None, dir=None)
path = None
with tempfile.TemporaryDirectory() as td:
path = td
print(path) # => C:\Users\name\AppData\Local\Temp\tmpdfvdrov6
f = pathlib.Path(path,'test.txt')
f.touch()
print(f.is_file()) # => True
print(pathlib.Path(path).exists()) # => False
mkstemp(suffix=None, prefix=None, dir=None, text=False)
import os
try:
hint, path = tempfile.mkstemp()
f = pathlib.Path(path)
f.write_text("あいうえお",encoding='utf8')
print(f.read_text(encoding='utf8')) # => あいうえお
print(f.exists()) # => True
finally:
if f is not None and f.exists():
os.close(hint)
os.remove(path)
print(path) # => C:\Users\name\AppData\Local\Temp\tmp_lrv7som
print(f.exists()) # => False
mkdtemp(suffix=None, prefix=None, dir=None)
import os
try:
dir_path = tempfile.mkdtemp()
d = pathlib.Path(dir_path)
print(dir_path) # => C:\Users\name\AppData\Local\Temp\tmpdvbbwlcu
print(d.exists()) # => True
finally:
if d is not None and d.exists():
d.rmdir()
print(d.exists()) # => False
tempfile.gettempdir() # => C:\Users\name\AppData\Local\Temp
Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?
コメント