Python语言之Python模块学习——tempfile
小标 2018-08-08 来源 : 阅读 1746 评论 0

摘要:本文主要向大家介绍了Python语言之Python模块学习——tempfile,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。

本文主要向大家介绍了Python语言之Python模块学习——tempfile,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。

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


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)     # Clean up the temporary file yourself
 
print
print 'TemporaryFile:'
temp = tempfile.TemporaryFile()
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()  # Automatically cleans up the file








这个例子说明了普通创建文件的方法与TemporaryFile()的不同之处,注意:用TemporaryFile()创建的文件没有文件名
 
$ python tempfile_TemporaryFile.py
 
Building a file name yourself:
temp: 
temp.name: /tmp/guess_my_name.14932.txt
 
TemporaryFile:
temp: 
temp.name: 
 
默认情况下使用w+b权限创建文件,在任何平台中都是如此,并且程序可以对它进行读写。
 

import os
import tempfile
 
temp = tempfile.TemporaryFile()
try:
    temp.write('Some data')
    temp.seek(0)
     
    print temp.read()
finally:
    temp.close()








写入侯,需要使用seek(),为了以后读取数据。
 
 
$ python tempfile_TemporaryFile_binary.py
 
Some data
如果你想让文件以text模式运行,那么在创建的时候要修改mode为'w+t'
 

import tempfile
 
f = tempfile.TemporaryFile(mode='w+t')
try:
    f.writelines(['first\n', 'second\n'])
    f.seek(0)
 
    for line in f:
        print line.rstrip()
finally:
    f.close()








$ python tempfile_TemporaryFile_text.py
 
first
second
tempfile.NamedTemporaryFile
如果临时文件会被多个进程或主机使用,那么建立一个有名字的文件是最简单的方法。这就是NamedTemporaryFile要做的,可以使用name属性访问它的名字
 



import os
import tempfile
 
temp = tempfile.NamedTemporaryFile()
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    # Automatically cleans up the file
    temp.close()
print 'Exists after close:', os.path.exists(temp.name)








尽管文件带有名字,但它仍然会在close后自动删除
 
$ python tempfile_NamedTemporaryFile.py
 
temp: 
temp.name: /var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmp0zHZvX
Exists after close: False
tempfile.mkdtemp
创建临时目录,这个不多说,直接看例子
 


import os
import tempfile
 
directory_name = tempfile.mkdtemp()
print directory_name
# Clean up the directory yourself
os.removedirs(directory_name)








$ python tempfile_mkdtemp.py
 
/var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmpB1CR8M
目录需要手动删除。
 
Predicting Names
用3个参数来控制文件名,名字产生公式:dir + prefix + random + suffix
 


import tempfile
 
temp = tempfile.NamedTemporaryFile(suffix='_suffix', 
                                   prefix='prefix_', 
                                   dir='/tmp',
                                   )
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()








$ python tempfile_NamedTemporaryFile_args.py
 
temp: 
temp.name: /tmp/prefix_UyCzjc_suffix
 
 
tempfile.mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])
    mkstemp方法用于创建一个临时文件。该方法仅仅用于创建临时文件,调用tempfile.mkstemp函数后,返回包含两个元素的元组,第一个元素指示操作该临时文件的安全级别,第二个元素指示该临时文件的路径。参数suffix和prefix分别表示临时文件名称的后缀和前缀;dir指定了临时文件所在的目录,如果没有指定目录,将根据系统环境变量TMPDIR, TEMP或者TMP的设置来保存临时文件;参数text指定了是否以文本的形式来操作文件,默认为False,表示以二进制的形式来操作文件。
tempfile.mktemp([suffix=''[, prefix='tmp'[, dir=None]]])
    mktemp用于返回一个临时文件的路径,但并不创建该临时文件。
tempfile.tempdir
    该属性用于指定创建的临时文件(夹)所在的默认文件夹。如果没有设置该属性或者将其设为None,Python将返回以下环境变量TMPDIR, TEMP, TEMP指定的目录,如果没有定义这些环境变量,临时文件将被创建在当前工作目录。
tempfile.gettempdir()
    gettempdir()则用于返回保存临时文件的文件夹路径。

本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved