You're reading your paths from a file with a path per line, but you didn't strip the newlines from each string, so you're looking for files that include a newline character, . As your error message notes, the invalid path was:\n
'C:\\Test\\Project1\n' <-- Single slash followed by n; directories are double slash separated
Strip them off as you read, and you'll be fine:
for line in infile:
line = line.rstrip("\r\n") # Removes all trailing carriage returns and newlines
if line[0] == "R":
Expansion of my comment: Why put the API to extra work parsing and testing against a filter pattern when you could just... not?
is better when you need to make use of the filtering feature and the filter is simple and string-based, as it simplifies the work. Sure, hand-writing simple matches (filtering glob via iterdir instead of if path.endswith('.txt'):) might be more efficient than the regex based pattern matching glob('*.txt') hides, but it's generally not worth the trouble of reinventing the wheel given that disk I/O is orders of magnitude slower.glob
But if you don't need the filtering functionality at all, don't use it. is gaining you nothing in terms of code simplicity or functionality, and hurting performance, so just use glob.iterdir
I guess you should use . Path.iterdir()
for pth in dir_.iterdir():
#Do your stuff here
I think you want:
for a in source_path.glob("*/*/*"):
if a.is_dir():
print(a)
From the documentation: The pattern means “this directory and all subdirectories, recursively”, whereas one ** is a text wildcard.*
As you already know, the only two methods for removing files/directories are Path and .unlink() and neither does what you want..rmdir()
Pathlib is a module that provides object oriented paths across different OS's, it isn't meant to have lots of diverse methods.
The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them.
The "uncommon" file system alterations, such as recursively removing a directory, is stored in different modules. If you want to recursively remove a directory, you should use the module. (It works with shutil instances too!)Path
import shutil
import pathlib
import os # for checking results
print(os.listdir())
# ["a_directory", "foo.py", ...]
path = pathlib.Path("a_directory")
shutil.rmtree(path)
print(os.listdir())
# ["foo.py", ...]