python標准庫介紹——17 tempfile 模塊詳解


==tempfile 模塊==


[Example 2-6 #eg-2-6] 中展示的 ``tempfile`` 模塊允許你快速地創建名稱唯一的臨時文件供使用.

====Example 2-6. 使用 tempfile 模塊創建臨時文件====[eg-2-6]

```
File: tempfile-example-1.py

import tempfile
import os

tempfile = tempfile.mktemp()

print "tempfile", "=>", tempfile

file = open(tempfile, "w+b")
file.write("*" * 1000)
file.seek(0)
print len(file.read()), "bytes"
file.close()

try:
    # must remove file when done
    os.remove(tempfile)
except OSError:
    pass

tempfile => C:\TEMP\~160-1
1000 bytes
```

``TemporaryFile`` 函數會自動挑選合適的文件名, 並打開文件, 如 [Example 2-7 #eg-2-7] 所示. 
而且它會確保該文件在關閉的時候會被刪除. (在 Unix 下, 你可以刪除一個已打開的文件, 這
時文件關閉時它會被自動刪除. 在其他平台上, 這通過一個特殊的封裝類實現.) 

====Example 2-7. 使用 tempfile 模塊打開臨時文件====[eg-2-7]

```
File: tempfile-example-2.py

import tempfile

file = tempfile.TemporaryFile()

for i in range(100):
    file.write("*" * 100)

file.close() # removes the file!
```

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM