VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python入门 >
  • python入门教程之Python3标准库:tempfile临时文件系统对象(2)

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


temp: {!r}'.format(temp))
  •  
  • for i in range(3):
  • temp.write('This line is repeated over and over.\n')
  • print(temp._rolled, temp._file)
  • print('rolling over')
  • temp.rollover()
  • print(temp._rolled, temp._file)
  • 在这个例子中,由于缓冲区非常大,远远大于实际的数据量,所以除非调用rollover(),否则不会在磁盘上创建任何文件。

    1.4 临时目录

    需要多个临时文件时,可能更方便的做法是用TemporaryDirectory创建一个临时目录,并打开该目录中的所有文件。 

    
    
    1. import pathlib
    2. import tempfile
    3.  
    4. with tempfile.TemporaryDirectory() as directory_name:
    5. the_dir = pathlib.Path(directory_name)
    6. print(the_dir)
    7. a_file = the_dir / 'a_file.txt'
    8. a_file.write_text('This file is deleted.')
    9.  
    10. print('Directory exists after?', the_dir.exists())
    11. print('Contents after:', list(the_dir.glob('*')))

    上下文管理器会生成目录名,可以在上下文块中用来建立其他文件名。

    1.5 临时文件位置

    如果没有使用dir参数指定明确的目标位置,则临时文件使用的路径会根据当前平台和设置而变化。tempfile模块包括两个函数来查询运行时使用的设置。

    
    
    1. import tempfile
    2.  
    3. print('gettempdir():', tempfile.gettempdir())
    4. print('gettempprefix():', tempfile.gettempprefix())

    gettempdir()返回包含所有临时文件的默认目录,gettempprefix()返回新文件和目录名和字符串前缀。

    gettempdir()返回的值根据一个简单算法来设置,它会查找一个位置列表,寻找第一个允许当前进程创建文件的位置。

    
    
    1. import tempfile
    2.  
    3. tempfile.tempdir = '/I/changed/this/path'
    4. print('gettempdir():', tempfile.gettempdir())

    如果程序需要对所有临时文件使用一个全局位置,但不使用以上任何环境变量,则应当直接设置tempfile.tempdir,为该变量赋一个值。

    相关教程
            
    关于我们--广告服务--免责声明--本站帮助-友情链接--版权声明--联系我们       黑ICP备07002182号