【问题标题】:Generate temporary Directory with files in Python for unittesting使用 Python 中的文件生成临时目录以进行单元测试
【发布时间】:2021-12-09 20:13:10
【问题描述】:

我想创建一个包含目录和一些文件的临时文件夹:

import os
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
    Path('file.txt').touch()
    Path('file2.txt').touch()

    files_in_dir = os.listdir(tmp_dir)
    print(files_in_dir)


Expected: [file.txt,file2.txt]
Result: []

有人知道如何在 Python 中做到这一点吗?还是有更好的方法来做一些嘲笑?

【问题讨论】:

  • 你正在接触当前工作目录中的那些文件,你可能想要Path(tmp_dir).joinpath('file.txt').touch()

标签: pytest python-unittest pytest-mock temporary-directory


【解决方案1】:

您必须通过获取tmp_dir 的路径在目录中创建文件。 with 上下文不适合你。

with tempfile.TemporaryDirectory() as tmp_dir:
    Path(tmp_dir, 'file.txt').touch()
    Path(tmp_dir, 'file2.txt').touch()
    files_in_dir = os.listdir(tmp_dir)
    print(files_in_dir)

# ['file2.txt', 'file.txt']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    相关资源
    最近更新 更多