Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.walk in Python is returning an empty list

Tags:

python

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:

enter image description here

What am I missing or doing wrong? Thanks!

like image 482
miquiztli_ Avatar asked May 19 '26 03:05

miquiztli_


2 Answers

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 []!

like image 62
raspiduino Avatar answered May 21 '26 16:05

raspiduino


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.

like image 29
astrochun Avatar answered May 21 '26 15:05

astrochun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!