python 的tempfile学习

本文介绍了如何在Python中使用`tempfile`模块创建和管理临时文件。通过具体实例展示了手动构建文件名的方式以及利用`tempfile.TemporaryFile()`函数自动生成临时文件的方法。此外,还说明了该函数创建的文件在关闭后会自动删除的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
print  "buildint a file using tempfile"
t = tempfile.TemporaryFile()
try:
    print 'temp:',temp
    print 'temp.name',temp.name
finally:
    temp.close()
building a file name yourself:
temp: <open file '/tmp/guess_my_name.24462.txt', mode 'w+b' at 0x103567db0>
temp.name /tmp/guess_my_name.24462.txt
buildint a file using tempfile
temp: <closed file '/tmp/guess_my_name.24462.txt', mode 'w+b' at 0x103567db0>
temp.name /tmp/guess_my_name.24462.txt

使用tempfile.TemporarFile函数来创建的临时文件,其他的应用程序无法找到或打开这个文件,因为它并没有引用文件系统表。

这个函数创建的临时文件,关闭后自动删除。

=============

tempfile.TemporarFile默认情况下使用w+b权限来创建文件;

使用temp.seek来重定位,方便以后读取数据

import os
import tempfile

temp = tempfile.TemporaryFile()

try:
    temp.write('some data')
    temp.seek(0)

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

  ===========

 

转载于:https://www.cnblogs.com/li-daphne/p/7019729.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值