zoukankan      html  css  js  c++  java
  • 如何正确使用Python临时文件

    摘要:临时文件通常用来保存无法保存在内存中的数据,或者传递给必须从文件读取的外部程序。一般我们会在/tmp目录下生成唯一的文件名,但是安全的创建临时文件并不是那么简单,需要遵守许多规则。

    1、前言

    临时文件通常用来保存无法保存在内存中的数据,或者传递给必须从文件读取的外部程序。一般我们会在/tmp目录下生成唯一的文件名,但是安全的创建临时文件并不是那么简单,需要遵守许多规则。永远不要自己去尝试做这件事,而是要借助库函数实现。而且也要小心清理临时文件。

    临时文件引起的最大问题就是,可以预测文件名,导致恶意用户可以预测临时文件名,从而创建软链接劫持临时文件。

    2. tempfile模块介绍

    创建临时文件一般使用的模块就是tempfile,此模块库函数常用的有以下几个:

    • tempfile.mktemp # 不安全,禁止使用
    • tempfile.mkstemp # 随机创建tmp文件,默认创建的文件在/tmp目录,当然也可以指定(可以使用)
    • tempfile.TemporaryFile # 内存中创建文件,文件不会存储在磁盘,关闭后即删除(可以使用)
    • tempfile.NamedTemporaryFile(delete=True) 当delete=True时,作用跟上面一样,当是False时,会存储在磁盘(可以使用)

    3. 示例介绍

    以下几种方式分别介绍了安全的创建临时文件及不安全的方式。

    3.1 不正确示例:

    不正确1:

    import os
    import tempfile
     
    # This will most certainly put you at risk
    tmp = os.path.join(tempfile.gettempdir(), filename)
    if not os.path.exists(tmp):
        with open(tmp, "w") file:
            file.write("defaults")

    不正确2:

    import os
    import tempfile
     
    open(tempfile.mktemp(), "w")

    不正确3:

    filename = "{}/{}.tmp".format(tempfile.gettempdir(), os.getpid())
    open(filename, "w")

    3.2 正确示例

    正确1:

    fd, path = tempfile.mkstemp()
    try:
        with os.fdopen(fd, 'w') as tmp:
            # do stuff with temp file
            tmp.write('stuff')
    finally:
        os.remove(path)

    正确2:

    # 句柄关闭,文件即删除
    with tempfile.TemporaryFile() as tmp:
        # Do stuff with tmp
        tmp.write('stuff')

    正确3:

    tmp = tempfile.NamedTemporaryFile(delete=True)
    try:
        # do stuff with temp
        tmp.write('stuff')
    finally:
        tmp.close()  # 文件关闭即删除
     

    本文分享自华为云社区《Python 临时文件那些事》,原文作者:技术火炬手。

     

    点击关注,第一时间了解华为云新鲜技术~

  • 相关阅读:
    Apache-Shiro分布式环境配置(与redis集成)(转)
    springboot整合mybatis将sql打印到日志(转)
    springboot中logback打印日志(转)
    Spring Boot Junit单元测试
    玩转Spring Boot 自定义配置、导入XML配置与外部化配置
    Windows开机自启动位置
    木马开机启动的六种方法(记录)
    用Delphi开发视频聊天软件
    Delphi用Socket API实现路由追踪
    前端工程师应该都了解的16个最受欢迎的CSS框架
  • 原文地址:https://www.cnblogs.com/huaweiyun/p/14576465.html
Copyright © 2011-2022 走看看