前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python开发_tempfile

python开发_tempfile

作者头像
Hongten
发布2018-09-13 12:30:27
7090
发布2018-09-13 12:30:27
举报
文章被收录于专栏:Hongten

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

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

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

后会自动删除。

下面是我做的demo:

运行效果:

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

代码部分:

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

代码语言:javascript
复制
 1 #python tempfile
 2 
 3 '''
 4     import tempfile
 5     
 6     如何你的应用程序需要一个临时文件来存储数据,
 7     但不需要同其他程序共享,那么用TemporaryFile
 8     函数创建临时文件是最好的选择。其他的应用程序
 9     是无法找到或打开这个文件的,因为它并没有引用
10     文件系统表。用这个函数创建的临时文件,关闭后
11     会自动删除。
12 '''
13 
14 import os
15 import tempfile
16 
17 def make_file():
18     '''创建临时文件,不过创建后,需要手动移除
19         os.remove(file)
20     '''
21     file_name = 'c:\\tmp\\test.%s.txt' % os.getpid()
22     temp = open(file_name, 'w+b')
23     try:
24         print('temp : {}'.format(temp))
25         print('temp.name : {}'.format(temp.name))
26         temp.write(b'hello, I\'m Hongten')
27         temp.seek(0)
28         print('#' * 50)
29         print('content : {}'.format(temp.read()))
30     finally:
31         temp.close()
32         #os.remove(file_name)
33 
34 def make_temp_file():
35     '''创建临时文件,在关闭的时候,系统会自动清除文件'''
36     temp = tempfile.TemporaryFile()
37     try:
38         print('temp : {}'.format(temp))
39         print('temp.name : {}'.format(temp.name))
40         temp.write(b'hello, I\'m Hongten')
41         temp.seek(0)
42         print('#' * 50)
43         print('content : {}'.format(temp.read()))
44     finally:
45         temp.close()  #then the system will automatically cleans up the file
46 
47 def main():
48     make_file()
49     print('#' * 50)
50     make_temp_file()
51     
52 if __name__ == '__main__':
53     main()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2013-08-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档