あるフリーランスエンジニアの色んなメモ!! ITスキル・ライフハックとか

Python:PermissionError: [Errno 13] Permission denied: 'C:\Users\user\AppData\Local\Temp\tmpavj2d07f'

事象

コード例

from tempfile import TemporaryFile

with TemporaryFile(mode='w') as f:
    f.write(...)

    # ファイル読込処理
    my_func(f.name)

with句内でファイル読込処理に対してTemporaryFileを渡す処理を
Windows上で実行すると、以下のエラーが発生する

E           PermissionError: [Errno 13] Permission denied: 'C:\\Users\\user\\AppData\\Local\\Temp\\tmpavj2d07f'

原因

WindowsではTemporaryFileを開いている状態で再度ファイルを開くことが出来ない

https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile
Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).


対策

以下の実装に変更する

  • TemporaryFileを「delete=False」を付けて開く
  • with句外でファイル読込処理に対してTemporaryFileを渡す
  • ファイルは手動で削除する

コード例

with TemporaryFile(mode='w', delete=False) as f:
    f.write(...)

# ファイル読込処理
my_func(f.name)

# ファイル削除
os.unlink(f.name)
comments powered by Disqus