简体   繁体   中英

os.walk in Python is returning an empty list

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM