国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python tempfile模塊學習筆記(臨時文件)

2020-02-23 05:22:33
字體:
來源:轉載
供稿:網友

tempfile.TemporaryFile

如何你的應用程序需要一個臨時文件來存儲數據,但不需要同其他程序共享,那么用TemporaryFile函數創建臨時文件是最好的選擇。其他的應用程序是無法找到或打開這個文件的,因為它并沒有引用文件系統表。用這個函數創建的臨時文件,關閉后會自動刪除。

實例一:
代碼如下:
import os
import tempfile

print 'Building a file name yourself:'
filename = '/tmp/guess_my_name.%s.txt' % os.getpid()
temp = open(filename, 'w+b')
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()
    os.remove(filename)     # Clean up the temporary file yourself

print
print 'TemporaryFile:'
temp = tempfile.TemporaryFile()
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()  # Automatically cleans up the file

這個例子說明了普通創建文件的方法與TemporaryFile()的不同之處,注意:用TemporaryFile()創建的文件沒有文件名

輸出:
代碼如下:
$ python tempfile_TemporaryFile.py


Building a file name yourself:

temp: <open file '/tmp/guess_my_name.14932.txt', mode 'w+b' at 0x1004481e0>

temp.name: /tmp/guess_my_name.14932.txt


TemporaryFile:

temp: <open file '<fdopen>', mode 'w+b' at 0x1004486f0>

temp.name: <fdopen>

 

默認情況下使用w+b權限創建文件,在任何平臺中都是如此,并且程序可以對它進行讀寫。這個例子說明了普通創建文件的方法與TemporaryFile()的不同之處,注意:用TemporaryFile()創建的文件沒有文件名


代碼如下:
$ python tempfile_TemporaryFile.py

Building a file name yourself:

temp: <open file '/tmp/guess_my_name.14932.txt', mode 'w+b' at 0x1004481e0>

temp.name: /tmp/guess_my_name.14932.txt

TemporaryFile:

temp: <open file '<fdopen>', mode 'w+b' at 0x1004486f0>

temp.name: <fdopen>

默認情況下使用w+b權限創建文件,在任何平臺中都是如此,并且程序可以對它進行讀寫。

實例二:
代碼如下:
import os
import tempfile

temp = tempfile.TemporaryFile()
try:
    temp.write('Some data')
    temp.seek(0)

    print temp.read()
finally:
    temp.close()

寫入侯,需要使用seek(),為了以后讀取數據。

輸出:
代碼如下:

$ python tempfile_TemporaryFile_binary.py

Some data
如果你想讓文件以text模式運行,那么在創建的時候要修改mode為'w+t'。

實例三:
代碼如下:
import tempfile

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 双江| 绍兴市| 镇原县| 翁源县| 监利县| 云安县| 桂平市| 临城县| 延寿县| 三台县| 娱乐| 邯郸县| 漳平市| 兴化市| 浑源县| 怀来县| 伊宁市| 师宗县| 新宁县| 芷江| 横峰县| 伊春市| 古浪县| 临泉县| 榆林市| 宜春市| 乌兰浩特市| 黑龙江省| 通许县| 阳谷县| 新田县| 崇左市| 双牌县| 睢宁县| 如皋市| 易门县| 和硕县| 定西市| 定西市| 阿城市| 明水县|