python3临时目录()文件名无效

2024-06-26 14:14:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python3中的临时目录中创建临时文件,但在windows中运行该程序时,我得到一个[WinError267]目录名无效 我认为这是由于文件命名中的windows“”造成的,但我使用了join功能来命名

with tempfile.TemporaryDirectory() as tdp:
    path = os.path.join(tdp, "tempfile.txt")
    tfp = open(path, "w+t")
    tfp.write("This is a temp file in temp dir")
    tfp.seek(0)
    print(tfp.read())

Tags: 文件path程序功能目录windowstempfile命名
1条回答
网友
1楼 · 发布于 2024-06-26 14:14:11

由于某些原因,您的代码仅在Windows上通过在打开的文件中使用with(您无论如何都应该使用该文件)工作(在修复缩进之后)

import tempfile
import os

with tempfile.TemporaryDirectory() as tdp:
    path = os.path.join(tdp, "tempfile.txt")
    with open(path, "w+t") as tfp:
        tfp.write("This is a temp file in temp dir")
        tfp.seek(0)
        print(tfp.read())

如果文件名不重要,只需使用tempfile.TemporaryFile

with tempfile.TemporaryFile(mode="w+t") as tfp:
    tfp.write("This is a temp file in temp dir")
    tfp.seek(0)
    print(tfp.read())

相关问题 更多 >