1. 程式人生 > >Python模組學習——tempfile

Python模組學習——tempfile

主要有以下幾個函式:

tempfile.TemporaryFile

如何你的應用程式需要一個臨時檔案來儲存資料,但不需要同其他程式共享,那麼用TemporaryFile函式建立臨時檔案是最好的選擇。其他的應用程式是無法找到或開啟這個檔案的,因為它並沒有引用檔案系統表。用這個函式建立的臨時檔案,關閉後會自動刪除。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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許可權建立檔案,在任何平臺中都是如此,並且程式可以對它進行讀寫。

1

2

3

4

5

6

7

8

9

10

11

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'

1

2

3

4

5

6

7

8

9

10

11

import tempfile

f = tempfile.TemporaryFile(mode='w+t')

try:

f.writelines(['first\n', 'second\n'])

f.seek(0)

for line in f:

print line.rstrip()

finally:

f.close()

$ python tempfile_TemporaryFile_text.py

first

second

tempfile.NamedTemporaryFile

如果臨時檔案會被多個程序或主機使用,那麼建立一個有名字的檔案是最簡單的方法。這就是NamedTemporaryFile要做的,可以使用name屬性訪問它的名字

1

2

3

4

5

6

7

8

9

10

11

import os

import tempfile

temp = tempfile.NamedTemporaryFile()

try:

print 'temp:', temp

print 'temp.name:', temp.name

finally:

# Automatically cleans up the file

temp.close()

print 'Exists after close:', os.path.exists(temp.name)

儘管檔案帶有名字,但它仍然會在close後自動刪除

$ python tempfile_NamedTemporaryFile.py

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

temp.name: /var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmp0zHZvX

Exists after close: False

tempfile.mkdtemp

建立臨時目錄,這個不多說,直接看例子

1

2

3

4

5

6

7

import os

import tempfile

directory_name = tempfile.mkdtemp()

print directory_name

# Clean up the directory yourself

os.removedirs(directory_name)

$ python tempfile_mkdtemp.py

/var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmpB1CR8M

目錄需要手動刪除。

Predicting Names

用3個引數來控制檔名,名字產生公式:dir + prefix + random + suffix

1

2

3

4

5

6

7

8

9

10

11

import tempfile

temp = tempfile.NamedTemporaryFile(suffix='_suffix',

prefix='prefix_',

dir='/tmp',

)

try:

print 'temp:', temp

print 'temp.name:', temp.name

finally:

temp.close()

$ python tempfile_NamedTemporaryFile_args.py

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

temp.name: /tmp/prefix_UyCzjc_suffix

tempfile.mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])

    mkstemp方法用於建立一個臨時檔案。該方法僅僅用於建立臨時檔案,呼叫tempfile.mkstemp函式後,返回包含兩個元素的元組,第一個元素指示操作該臨時檔案的安全級別,第二個元素指示該臨時檔案的路徑。引數suffix和prefix分別表示臨時檔名稱的字尾和字首;dir指定了臨時檔案所在的目錄,如果沒有指定目錄,將根據系統環境變數TMPDIRTEMP或者TMP的設定來儲存臨時檔案;引數text指定了是否以文字的形式來操作檔案,預設為False,表示以二進位制的形式來操作檔案。

tempfile.mktemp([suffix=''[, prefix='tmp'[, dir=None]]])

    mktemp用於返回一個臨時檔案的路徑,但並不建立該臨時檔案。

tempfile.tempdir

    該屬性用於指定建立的臨時檔案(夾)所在的預設資料夾。如果沒有設定該屬性或者將其設為None,Python將返回以下環境變數TMPDIR, TEMP, TEMP指定的目錄,如果沒有定義這些環境變數,臨時檔案將被建立在當前工作目錄。

tempfile.gettempdir()

    gettempdir()則用於返回儲存臨時檔案的資料夾路徑。