Python:无法创建子目录

2024-09-29 04:28:43 发布

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

我想对文件列表应用测试。通过测试的文件应移到“Pass”目录下;其他文件应移到“Fail”目录下。你知道吗

因此,输出目录应该包含子目录“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)

但是,我的代码是将文件移动到输出目录,而不是创建“Pass”或“Fail”子目录。知道为什么吗?你知道吗


Tags: 文件目录列表scanifdirpassdest
2条回答

使用操作系统路径连接(). 示例:

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)

只创建一次目录:

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。你知道吗

相关问题 更多 >