首页 > 解决方案 > 如何在临时目录中写入和读取 txt 文件?

问题描述

我想要一个临时目录和一个 txt 文件,一旦临时目录关闭,该文件将被删除。但是当我尝试编写一个 txt 文件(在临时目录中创建)时,没有写入 txt 文件,其中没有内容。

例子:

import tempfile

message = 'this is my message'

with tempfile.TemporaryDirectory(dir='../', prefix='temp_') as td:
    td = td.replace(chr(92), '/')
    with open(f'{td}/filename.txt', 'w+') as temporary_file:
        temporary_file.write(message)
        temporary_file.read()
        # do some stuff here
# the temporary directory was closed, removing the txt file.

标签: pythontemporary-files

解决方案


推荐阅读