VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python入门 >
  • python入门教程之Python3标准库:tempfile临时文件系统对象

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


1. tempfile临时文件系统对象

要想安全的创建名字唯一的临时文件,以防止被试图破坏应用或窃取数据的人猜出,这很有难度。tempfile模块提供了多个函数来安全的创建临时文件系统资源。TemporaryFile()打开并返回一个未命名的文件,NamedTemporaryFile()打开并返回一个命名文件,SpooledTemporaryFile在将内容写入磁盘之前先将其保存在内存中,TemporaryDirectory是一个上下文管理器,上下文关闭时会删除这个目录。

1.1 临时文件

如果应用需要临时文件来存储数据,而不需要与其他程序共享这些文件,则应当使用TemporaryFile()函数创建文件。这个函数会创建一个文件,而且如果平台支持,它会立即断开这个新文件的链接。这样一来,其他程序就不可能找到或打开这个文件,因为文件系统表中根本没有这个文件的引用。对于TemporaryFile()创建的文件,无论通过调用close()还是结合使用上下文管理器API和with语句,关闭文件时都会自动删除这个文件。


  1. import os
  2. import tempfile
  3.  
  4. print('Building a filename with PID:')
  5. filename = '/guess_my_name.{}.txt'.format(os.getpid())
  6. with open(filename, 'w+b') as temp:
  7. print('temp:')
  8. print(' {!r}'.format(temp))
  9. print('temp.name:')
  10. print(' {!r}'.format(temp.name))
  11.  
  12. # Clean up the temporary file yourself.
  13. os.remove(filename)
  14.  
  15. print()
  16. print('TemporaryFile:')
  17. with tempfile.TemporaryFile() as temp:
  18. print('temp:')
  19. print(' {!r}'.format(temp))
  20. print('temp.name:')
  21. print(' {!r}'.format(temp.name))

这个例子展示了采用不同方法创建临时文件的差别,一种做法是使用一个通用模式来构造临时文件的文件名,另一种做法是使用TemporaryFile()函数。TemporaryFile()返回的文件没有文件名。

默认的,文件句柄是使用模式'w+b'创建的,以便它在所有平台上都表现一致,并允许调用者读写这个文件。 


  1. import os
  2. import tempfile
  3.  
  4. with tempfile.TemporaryFile() as temp:
  5. temp.write(b'Some data')
  6.  
  7. temp.seek(0)
  8. print(temp.read())

写文件之后,必需使用seek()"回转"文件句柄以便从文件读回数据。

要以文本模式打开文件,创建文件时要设置mode为'w+t'。


  1. import tempfile
  2.  
  3. with tempfile.TemporaryFile(mode='w+t') as f:
  4. f.writelines(['first\n', 'second\n'])
  5.  
  6. f.seek(0)
  7. for line in f:
  8. print(line.rstrip())

这个文件句柄将把数据处理为文本。

1.2 命名文件

有些情况下,可能非常需要一个命名的临时文件。对于跨多个进程甚至主机的应用来说,为文件命名是在应用不同部分之间传递文件的最简单的方法。NamedTemporaryFile()函数会创建一个文件,但不会断开它的链接,所以会保留它的文件名(用name属性访问)。 


  1. import os
  2. import pathlib
  3. import tempfile
  4.  
  5. with tempfile.NamedTemporaryFile() as temp:
  6. print('temp:')
  7. print(' {!r}'.format(temp))
  8. print('temp.name:')
  9. print(' {!r}'.format(temp.name))
  10.  
  11. f = pathlib.Path(temp.name)
  12.  
  13. print('Exists after close:', f.exists())

句柄关闭后文件将被删除。

1.3 假脱机文件

如果临时文件中包含的数据相对较少,则使用SpooledTemporaryFile可能更高效,因为它使用一个io.BytesIO或io.stringIO缓冲区在内存中保存内容,直到数据达到一个阈值时,数据将“滚动”并写入磁盘,然后用常规的TemporaryFile()替换这个缓冲区。 


  1. import tempfile
  2.  
  3. with tempfile.SpooledTemporaryFile(max_size=100,
  4. mode='w+t',
  5. encoding='utf-8') as temp:
  6. print('temp: {!r}'.format(temp))
  7.  
  8. for i in range(3):
  9. temp.write('This line is repeated over and over.\n')
  10. print(temp._rolled, temp._file)

这个例子使用SpooledTemporaryFile的私有属性来确定何时滚动到磁盘。除非要调整缓冲区大小,否则很少需要检查这个状态。

要显示的将缓冲区写至磁盘,可以调用rollover()或fileno()方法。 


  1. import tempfile
  2.  
  3. with tempfile.SpooledTemporaryFile(max_size=1000,
  4. mode='w+t',
  5. encoding='utf-8') as temp:
  6. print('
相关教程