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)
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)
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.
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.
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.)
You need to create the full path name before checking:
if not os.path.isdir(os.path.join(path, each)):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With