【问题标题】:checking if a directory exists, breaking out of loop检查目录是否存在,跳出循环
【发布时间】:2014-11-10 18:49:15
【问题描述】:

试图查看一个目录是否存在,如果它没有将目录移动到另一个目录,然后继续循环的下一个迭代,这就是我正在做的事情,设法让第一个循环工作,将目录移动到另一个时,仅在最后一部分正确创建所有文件,但会引发错误,错误和我的代码部分:

 File "testdraft.py", line 305, in findReplace
    if not os.path.exists('{}/'.format.replace+str(x)):shutil.move(str(x), '{}/'.format(replace))
AttributeError: 'builtin_function_or_method' object has no attribute 'replace'

 base_direct = '{}/'.format(replace)

 for x in range(1,20):
        if not os.path.exists(str(x)+'/'):os.mkdir(str(x)+'/') #this part works
        else: continue
        shutil.copy(filename, str(x))
        shutil.copy(filename1, str(x))
        frag = open("fragments_procs.in", 'w')
        frag.write(str(x) + "\n" + str(20-x))
        shutil.copy("fragments_procs.in", str(x))
        shutil.move(str(x), '{}/'.format(replace)) #believe from here and down not working
         if not os.path.exists('{}/'.format(replace)+str(x)):shutil.move(str(x), '{}/'.format(replace))
        else: continue

【问题讨论】:

  • 更好的模型是尝试进行文件移动并在失败时采取措施。否则,您正在创建竞争条件。
  • 我有一个像这样的函数“func1(replace, filename1, filename),这个函数被调用了 66 次,我试图只在那个循环中创建一个目录而不是 19,这就是为什么我创建第一个目录后继续

标签: python for-loop mkdir shutil


【解决方案1】:

您的代码相当混乱且难以理解,但无论如何在第 305 行有一个明显的语法错误

if not os.path.exists('{}/'.format.replace+str(x))

这根本没有意义。 str.format 函数没有任何名为 replace 的属性(顺便说一下,这是一个非常糟糕的变量名称,因为字符串有一个 replace 方法)

我的猜测是你想做这样的事情:

if not os.path.exists('{}{}/'.format(replace, x))

【讨论】:

  • 我修复了我的代码,缺少一个括号,替换是我的构造函数中的一个字符串。
【解决方案2】:

您可以使用walk,并且每次连接子目录。

for path, subdirs, files in os.walk(directory):
    for filename in files:
        print os.path.join(path, filename)

【讨论】:

    【解决方案3】:

    replace 是字符串的内置方法,因此将其用作变量名会使事情变得混乱

    '{}/'.format(replace+str(x))

    【讨论】:

    • 抱歉,刚刚解决了这个问题,replace 是我所在函数的构造函数的字符串部分。是的,代码非常混乱,我第一次创建 19 个目录,每个目录复制三个文件19 个目录,并将所有 19 个目录移动到最后一个目录中,即 /replace。
    猜你喜欢
    • 2020-08-09
    • 2015-03-31
    • 2017-10-17
    • 2021-02-20
    • 2019-06-24
    • 1970-01-01
    • 2015-12-10
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多