【问题标题】:Using tempfile to create a sub-directory for all of my tempfiles使用 tempfile 为我的所有临时文件创建一个子目录
【发布时间】:2012-01-13 19:23:25
【问题描述】:

我一直在使用带有前缀的tempfile.mkdtemp 来创建我的临时文件。这会导致我的 tmp 文件夹中有很多不同的目录,其中包含“tmp/myprefix{uniq-string}/”。

我想更改它并拥有一个子目录,以便我创建的临时文件夹都在一个主目录下,这样前缀实际上是tmp 'tmp/myprefix/{uniq-string}/' 的子文件夹。

另外,我不想覆盖tempfile 的系统来定义默认的 tmp 目录。

我尝试使用“prefix”和“dir”参数,但没有成功。

【问题讨论】:

    标签: python temporary-files


    【解决方案1】:

    要使用 dir 参数,您必须确保 dir 文件夹存在。像这样的东西应该可以工作:

    import os
    import tempfile
    
    #define the location of 'mytemp' parent folder relative to the system temp
    sysTemp = tempfile.gettempdir()
    myTemp = os.path.join(sysTemp,'mytemp')
    
    #You must make sure myTemp exists
    if not os.path.exists(myTemp):
        os.makedirs(myTemp)
    
    #now make your temporary sub folder
    tempdir = tempfile.mkdtemp(suffix='foo',prefix='bar',dir=myTemp)
    
    print tempdir
    

    【讨论】:

    • 我忘记了 gettempdir()。谢谢!
    • 其实 os.makedirs(myTemp, exist_ok=True) 可以自己去掉 if 检查
    • 3.2添加了exist_ok参数
    【解决方案2】:

    为我工作。您是否事先创建了tmp 文件夹?

    >>> import tempfile
    >>> tempfile.mkdtemp(dir="footest", prefix="fixpre")
    OSError: [Errno 2] No such file or directory: 'footest/fixpregSSaFg'
    

    看起来它确实尝试创建footest....的子文件夹

    【讨论】:

      猜你喜欢
      • 2013-06-21
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多