mktemp()是不推荐的,而且不安全。因此,我尝试将其升级到mkstemp()。
class TestUtils:
@contextmanager
def temp_dir(self):
tmp = tempfile.mkdtemp()
try:
yield tmp
finally:
shutil.rmtree(tmp)
@contextmanager
def temp_file(self):
with self.temp_dir() as tmp:
yield tempfile.mktemp(dir=tmp)
class CsvTest(PandasOnSparkTestCase, TestUtils):
def setUp(self):
self.tmp_dir = tempfile.mkdtemp(prefix=CsvTest.__name__)
def tearDown(self):
shutil.rmtree(self.tmp_dir, ignore_errors=True)
@contextmanager
def csv_file(self, csv):
with self.temp_file() as tmp:
with open(tmp, "w") as f:
f.write(csv)
yield tmp当我将yield tempfile.mktemp(dir=tmp)更改为yield tempfile.mkstemp(dir=tmp)时,它返回一个元组。
当我将它改为yield tempfile.NamedTemporaryFile(dir=tmp, delete=False)时,我得到了TypeError:预期的str、字节或os.PathLike对象,而不是_TemporaryFileWrapper
怎样才是正确的方法?
发布于 2022-03-08 17:32:43
来自文档
mkstemp()返回一个元组,该元组包含打开文件的操作系统级句柄(正如os.open()将返回的那样)以及该文件的绝对路径名。
mktemp()只返回路径名。因此,如果您想与mktemp兼容,请使用
yield tempfile.mktemp(dir=tmp)[1]返回路径名。
发布于 2022-03-08 17:36:36
试着使用
yield tempfile.mktemp(dir=tmp)[1]https://stackoverflow.com/questions/71399020
复制相似问题