python3.x为演示例子
In [2]: from tempfile import TemporaryFile,NamedTemporaryFile 使用TemporaryFile是无法在文件系统中找到文件的路径的 In [15]: TemporaryFile? Type: function String form: <function TemporaryFile at 0xb6f0dc8c> File: /usr/lib/python3.6/tempfile.py Definition: TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None) Docstring: Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). 'buffering' -- the buffer size argument to io.open (default -1). 'encoding' -- the encoding argument to io.open (default None) 'newline' -- the newline argument to io.open (default None) The file is created as mkstemp() would do it. Returns an object with a file-like interface. The file has no name, and will cease to exist when it is closed. 返回具有类文件接口的对象;文件的名称。 可以作为它的“名称”属性访问。该文件将自动 在关闭时删除,除非“删除”参数被设置为false。 In [3]: f = TemporaryFile() In [4]: f.write(b'abcdefg' * 10000) Out[4]: 70000 In [5]: f.seek(0) Out[5]: 0 In [6]: f.read(100) Out[6]: b'abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgab' In [7]: f.read(100) Out[7]: b'cdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcd' 使用NamedTemporaryFile可以在/tmp下找到对应的临时文件,并且每次会进行垃圾回收文件,将临时文件删除.也可以指定不删除 In [25]: NamedTemporaryFile? Type: function String form: <function NamedTemporaryFile at 0xb6f0d9bc> File: /usr/lib/python3.6/tempfile.py Definition: NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True) Docstring: Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). 'buffering' -- the buffer size argument to io.open (default -1). 'encoding' -- the encoding argument to io.open (default None) 'newline' -- the newline argument to io.open (default None) 'delete' -- whether the file is deleted on close (default True). The file is created as mkstemp() would do it. Returns an object with a file-like interface; the name of the file is accessible as its 'name' attribute. The file will be automatically deleted when it is closed unless the 'delete' argument is set to False. (END) In [30]: ntf = NamedTemporaryFile(delete=False) In [31]: ls systemd-private-74481d0c1ebe4303a09b6046b394d120-systemd-timesyncd.service-P1tBJK/ tmpxv7mj204 VMwareDnD/ vmware-root/ In [34]: ntf = NamedTemporaryFile(delete=False) In [35]: ls systemd-private-74481d0c1ebe4303a09b6046b394d120-systemd-timesyncd.service-P1tBJK/ tmpiztvt55u tmpxv7mj204 VMwareDnD/ vmware-root/