記錄下來是因為當(dāng)時谷歌這個問題時發(fā)現(xiàn),網(wǎng)上也有很多人遇到這個問題,我也因為這個問題導(dǎo)致了一個bug,所以告誡自己以后使用API多仔細(xì)看看文檔。
python的tempfile模塊用于創(chuàng)建系統(tǒng)臨時文件,是一個很有用的模塊。通過tempfile.NamedTemporaryFile,可以輕易的創(chuàng)建臨時文件,并返回一個文件對象,文件名可以通過對象的name屬性獲取,且創(chuàng)建的臨時文件會在關(guān)閉后自動刪除。下面這段python代碼創(chuàng)建一個臨時文件,并再次打開該臨時文件,寫入數(shù)據(jù),然后再次打開,讀取文件,并按行打印文件內(nèi)容。
#!/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代碼,會創(chuàng)建一個臨時文件,且程序退出后該臨時文件會自動刪除,輸出如下:
root@master:demo$ python tmp_file.py
tmp file is /tmp/tmpb3EYGV
line 1
line 2
line 3
但是在windows上運行時,提示沒有權(quán)限,不能打開創(chuàng)建的臨時文件,是不是感覺很奇怪。
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).
大概意思是,當(dāng)這個臨時文件處于打開狀態(tài),在unix平臺,該名字可以用于再次打開臨時文件,但是在windows不能。所以,如果要在windows打開該臨時文件,需要將文件關(guān)閉,然后再打開,操作完文件后,再調(diào)用os.remove刪除臨時文件。