tempfile.NamedTemporaryFile創建臨時文件在windows沒有權限打開

記錄下來是因爲當時谷歌這個問題時發現,網上也有很多人遇到這個問題,我也因爲這個問題導致了一個bug,所以告誡自己以後使用API多仔細看看文檔。

python的tempfile模塊用於創建系統臨時文件,是一個很有用的模塊。通過tempfile.NamedTemporaryFile,可以輕易的創建臨時文件,並返回一個文件對象,文件名可以通過對象的name屬性獲取,且創建的臨時文件會在關閉後自動刪除。下面這段python代碼創建一個臨時文件,並再次打開該臨時文件,寫入數據,然後再次打開,讀取文件,並按行打印文件內容。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tempfile


# create tmp file and write it
tmp_file = tempfile.NamedTemporaryFile()
print 'tmp file is {self.name}'.format(self=tmp_file)

with open(tmp_file.name, 'w') as f:
    f.write("line 1\nline 2\nline 3\n")


# user tmp file
with open(tmp_file.name) as f:
    for line in f.readlines():
        print line

在linux上運行上面的python代碼,會創建一個臨時文件,且程序退出後該臨時文件會自動刪除,輸出如下:

root@master:demo$ python tmp_file.py
tmp file is /tmp/tmpb3EYGV
line 1

line 2

line 3

但是在windows上運行時,提示沒有權限,不能打開創建的臨時文件,是不是感覺很奇怪。

E:\share\git\python_practice\demo>tmp_file.py
tmp file is c:\users\leo\appdata\local\temp\tmphn2kqj
Traceback (most recent call last):
  File "E:\share\git\python_practice\demo\tmp_file.py", line 11, in <module>
    with open(tmp_file.name, 'w') as f:
IOError: [Errno 13] Permission denied: 'c:\\users\\leo\\appdata\\local\\temp\\tm
phn2kqj'

查看官方文檔,該API解釋如下:

tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the returned file-like object. 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). If delete is true (the default), the file is deleted as soon as it is closed.
The returned object is always a file-like object whose file attribute is the underlying true file object. This file-like object can be used in a with statement, just like a normal file.
New in version 2.3.
New in version 2.6: The delete parameter.

注意其中的一句話:

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).

大概意思是,當這個臨時文件處於打開狀態,在unix平臺,該名字可以用於再次打開臨時文件,但是在windows不能。所以,如果要在windows打開該臨時文件,需要將文件關閉,然後再打開,操作完文件後,再調用os.remove刪除臨時文件。

參考:https://docs.python.org/2/library/tempfile.html
發佈了63 篇原創文章 · 獲贊 11 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章