Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python not recognising directories os.path.isdir() [duplicate]

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)
like image 603
Dan Avatar asked Sep 21 '10 14:09

Dan


People also ask

What is OS path Isdir in Python?

path. isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows symbolic link, that means if the specified path is a symbolic link pointing to a directory then the method will return True. Syntax: os.path.isdir(path)

How do I get the path of a directory in Python?

In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.

How do you give a path to another directory in Python?

Changing the Current Working Directory in Python To change the current working directory in Python, use the chdir() method. The method accepts one argument, the path to the directory to which you want to change. The path argument can be absolute or relative.

How do you get the paths of all files in a folder in Python?

os. listdir() returns everything inside a directory -- including both files and directories. A bit simpler: (_, _, filenames) = walk(mypath). next() (if you are confident that the walk will return at least one value, which it should.)


1 Answers

You need to create the full path name before checking:

if not os.path.isdir(os.path.join(path, each)):
  ...
like image 80
unwind Avatar answered Oct 11 '22 13:10

unwind