如何在Python中创建tmp文件?

发布于 2021-01-29 18:58:31

我有引用文件路径的此函数:

some_obj.file_name(FILE_PATH)

其中FILE_PATH是文件路径的字符串,即 H:/path/FILE_NAME.ext

我想在python脚本中使用字符串内容创建文件FILE_NAME.ext:

some_string = 'this is some content'

怎么办呢?Python脚本将放置在Linux盒子中。

关注者
0
被浏览
138
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    有一个用于python的tempfile模块,但是创建一个简单的文件也可以解决这个问题:

    new_file = open("path/to/FILE_NAME.ext", "w")
    

    现在,您可以使用以下write方法对其进行写入:

    new_file.write('this is some content')
    

    使用tempfile模块,它可能看起来像这样:

    import tempfile
    
    new_file, filename = tempfile.mkstemp()
    
    print(filename)
    
    os.write(new_file, "this is some content")
    os.close(new_file)
    

    使用mkstemp完后,您有责任删除文件。使用其他参数,您可以影响文件的目录和名称。


    更新

    正如Emmet Speer正确指出的那样,使用时要考虑安全性mkstemp,因为客户端代码负责关闭/清理创建的文件。更好的方法是以下代码段(摘自链接):

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

    os.fdopen文件描述符包装在Python文件对象中,该文件对象会在with退出时自动关闭。os.remove不再需要时,调用删除文件。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看