I'm trying to use os.walk to return a list of .xlsx files from a directory, but it's returning an empty list.
import os
import pathlib
working_directory = 'N:/files path'
def find_filenames(path, suffix):
# First save all filenames in a list: file_list:
file_list = []
# Gets a list of all validation xlsx files in the folder:
for subdir, dirs, files in os.walk(path):
for file in files:
if file.endswith(suffix):
# save filesnames in file_list:
file_list.append(file)
return file_list
print(find_filenames(pathlib.Path(working_directory), '.xlsx')
It's printing this:
[]
When it should look like this:

What am I missing or doing wrong? Thanks!
Should it be:
import os
import pathlib
working_directory = 'N:/files path'
def find_filenames(path, suffix):
# First save all filenames in a list: file_list:
file_list = []
# Gets a list of all validation xlsx files in the folder:
for subdir, dirs, files in os.walk(path):
for file in files:
if file.endswith(suffix):
# save filesnames in file_list:
file_list.append(file)
return file_list
The problem is you have put the return in wrong place. If you put like the code in your question and if the first file is not end with .xlsx, it will directly return []!
While the above answer is correct and is the simplest fix, I wanted to recommend a suggestion. You're importing pathlib, which already has built-in recursive glob-ing. As such, you can simplify your code if your expectation is a Path object for path:
import pathlib
working_directory = 'N:/files path'
def find_filenames(path: pathlib.Path, suffix: str):
return list(path.rglob('*'+suffix))
print(find_filenames(pathlib.Path(working_directory), '.xlsx'))
rglob method will do recursive globbing here! Also, you would not need to import os for this snippet of code.
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