【问题标题】:Python: can't create subdirectoryPython:无法创建子目录
【发布时间】:2015-10-28 02:33:16
【问题描述】:

我想对文件列表应用测试。通过测试的文件应移至“通过”目录;其他的应该移到目录“失败”。

因此输出目录应该包含子目录“Pass”和“Fail”。

这是我的尝试:

        if(<scan==pass>) # Working fine up to this point
            dest_dir = outDir + '\\' + 'Pass'  # The problem is here
            print("Pass", xmlfile)
            MoveFileToDirectory(inDir, xmlfile, dest_dir)
        else:
            dest_dir = os.path.dirname(outDir + '\\' + 'Fail')
            print("Fail: ", xmlfile)
            MoveFileToDirectory(inDir, xmlfile, dest_dir)

但是,我的代码将文件移动到输出目录,而不是创建“通过”或“失败”子目录。任何想法为什么?

【问题讨论】:

  • if(&lt;scan==pass&gt;) 根本不是有效的语法,应该测试什么?
  • 你确定你的语法吗?忘记意图,&lt;...&gt; 做什么? pass 是一个关键字。你永远不应该将它用作变量。我认为你甚至不能......
  • 这是我根据我的程序使用的东西,例如我这样输入的。
  • 是的,我确定 pass 是小写的关键字,为了解决歧义,您可以使用 Passed。我的代码在发布时的标识很好,看起来像 this@hiro
  • @PadraicCunningham:我认为 OP 只是有一些古怪的情况,他试图让我们免于查看。这只是某种真/假条件,与真正的问题无关。

标签: python


【解决方案1】:

使用 os.path.join()。示例:

os.path.join(outDir, 'Pass')

See this SO post

另外,我们不知道MoveFileToDirectory 做了什么。使用标准os.rename

os.rename("path/to/current/file.foo", "path/to/new/desination/for/file.foo")

See this SO post

所以:

source_file = os.path.join(inDir, xmlfile)
if(conditionTrue):
    dest_file = os.path.join(outDir, 'Pass', xmlfile)
    print("Pass: ", xmlfile)
else:
    dest_file = os.path.join(outDir, 'File', xmlfile)
    print("Fail: ", xmlfile)
os.rename(source_file, dest_file)

【讨论】:

    【解决方案2】:

    只创建一次目录:

    import os
    
    labels = 'Fail', 'Pass'
    dirs = [os.path.join(out_dir, label) for label in labels]
    for d in dirs:
        try:
            os.makedirs(d)
        except EnvironmentError:
            pass # ignore errors
    

    然后您可以将文件移动到创建的目录中:

    import shutil
    
    print("%s: %s" % (labels[condition_true], xmlfile))
    shutil.move(os.path.join(out_dir, xmlfile), dirs[condition_true])
    

    代码利用了 Python 中的 False == 0True == 1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多