zoukankan      html  css  js  c++  java
  • python 的tempfile学习

    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()
    

      ===========

  • 相关阅读:
    java的replace和replaceAll
    hibernate必须的包下载以及各个包的作用
    Jquery退出循环
    JQuery解析XML数据的几个例子
    使用ajax获取servelt数据乱码
    jquery绝对路径
    LeetCode 368. Largest Divisible Subset
    LeetCode 413. Arithmetic Slices
    LeetCode 474. Ones and Zeroes
    LeetCode 486. Predict the Winner
  • 原文地址:https://www.cnblogs.com/li-daphne/p/7019729.html
Copyright © 2011-2022 走看看