I'm a Python beginner and looking for some help with searching a list of directories using os.walk.
The idea is that I'm pulling a list of directories from an SQL database, these directories will likely have different drive letters or even a UNC path. What I need to do is search through those directories to find a file of a specific name and delete it. As the file could be in any of the directories it needs to search them all. The list of directories is indefinite so my thought was to store them into a list and have os.walk look at all directories in that list.
def get_location():
c.execute('SELECT ADDRESS FROM DIRECTORY')
data = c.fetchall()
SQLlist = [row for row in data]
return SQLlist
addresslist = get_location()
def FileDeleter():
for root, dirs, files in chain.from_iterable(os.walk(addresslist[0:], topdown=False) for path in (str(addresslist[0:]))):
for file in files:
if correctID in file:
if file.endswith('.custextn'):
os.remove(os.path.join(root, file))
This is how the code currently stands, but previously I've tried:
for root, dirs, files in os.walk(addresslist[0:], topdown=False):
for root, dirs, files in chain.from_iterable(os.walk(addresslist[0:], topdown=False)):
It seems to be that os.walk doesn't accept lists (/ tuples). If I set addresslist[0] or addresslist[1] it actually works, however as I don't know how many addresses there potentially could be I unfortunately can't just store X addresses as separate variables and duplicate the function.
The error I get when running my code is:
'TypeError: expected str, bytes or os.PathLike object, not list'
Finally, I've tested with a hardcoded list of addresses just to rule out an issue with how the list is being extracted from the database, e.g.:
addresslist = ['C:\\Subfolder1\\Subfolder2', 'D:\\Subfolder1\\Subfolder2']
and, because of unpacking errors:
x,y = ['C:\\Subfolder1\\Subfolder2', 'D:\\Subfolder1\\Subfolder2']
Thanks