当前位置: 动力学知识库 > 问答 > 编程问答 >

file io - Python not recognising directories os.path.isdir()

问题描述:

I have the following Python code to remove files in a directory.

For some reason my .svn directories are not being recognised as directories.

And I get the following output:

.svn not a dir

Any ideas would be appreciated.

def rmfiles(path, pattern):

pattern = re.compile(pattern)

for each in os.listdir(path):

if os.path.isdir(each) != True:

print(each + " not a dir")

if pattern.search(each):

name = os.path.join(path, each)

os.remove(name)

网友答案:

You need to create the full path name before checking:

if not os.path.isdir(os.path.join(path, each)):
  ...
网友答案:

You will need to os.path.join the path you invoke listdir on with the found file/directory, i.e.

for each in os.listdir(path):
    if os.path.isdir(os.path.join(path, each)):
        ....

If you don't create an absolute path this way you will be testing against your current working directory in stead, which probably dioesn't have the svn directory.

Also, don't explicitly compare boolean values. Let if handle it as a boolean expression (some functions may return non True/False truth values, i.e. None or an instance)

网友答案:

You could also switch to the target directory instead of constructing an absolute path.

def rmfiles(path, pattern):
    pattern = re.compile(pattern)
    oldpath = os.getcwd()     # <--
    os.chdir(path)            # <--
    try:
      for each in os.listdir('.'):
        if os.path.isdir(each) != True:
            print(each +  " not a dir")
            if pattern.search(each):
                name = os.path.join(path, each)
                os.remove(name)
    finally:
      os.chdir(oldpath)       # <--
分享给朋友:
您可能感兴趣的文章:
随机阅读: