Python开发--tempfile

转载自http://www.cnblogs.com/hongten/p/hongten_python_tempfile.html

python中的tempfile模块,是为创建临时文件(夹)所提供的

 如果你的应用程序需要一个临时文件来存储数据,但不需要同其他程序共享,那么tempfile模块来创建临时文件(夹)是个不错的选择

其他的应用程序是无法找到活打开这个文件(夹),因为tempfile在创建的过程中没有引用文件系统表,用tempfile创建的临时文件(夹),关闭

后会自动删除。

下面是我做的demo:

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

代码部分:

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

#python tempfile

'''
    import tempfile
    
    如何你的应用程序需要一个临时文件来存储数据,
    但不需要同其他程序共享,那么用TemporaryFile
    函数创建临时文件是最好的选择。其他的应用程序
    是无法找到或打开这个文件的,因为它并没有引用
    文件系统表。用这个函数创建的临时文件,关闭后
    会自动删除。
'''

import os
import tempfile

def make_file():
    '''创建临时文件,不过创建后,需要手动移除
        os.remove(file)
    '''
    file_name = 'c:\\tmp\\test.%s.txt' % os.getpid()
    temp = open(file_name, 'w+b')
    try:
        print('temp : {}'.format(temp))
        print('temp.name : {}'.format(temp.name))
        temp.write(b'hello, I\'m Hongten')
        temp.seek(0)
        print('#' * 50)
        print('content : {}'.format(temp.read()))
    finally:
        temp.close()
        #os.remove(file_name)

def make_temp_file():
    '''创建临时文件,在关闭的时候,系统会自动清除文件'''
    temp = tempfile.TemporaryFile()
    try:
        print('temp : {}'.format(temp))
        print('temp.name : {}'.format(temp.name))
        temp.write(b'hello, I\'m Hongten')
        temp.seek(0)
        print('#' * 50)
        print('content : {}'.format(temp.read()))
    finally:
        temp.close()  #then the system will automatically cleans up the file

def main():
    make_file()
    print('#' * 50)
    make_temp_file()
    
if __name__ == '__main__':
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值