#Cannot load files

1 messages · Page 1 of 1 (latest)

dusk gale
#

Hello everyone, I have the following code:

for folder in os.listdir('./cogs'):
    for module in os.listdir(f'./cogs/{folder}'):
        for category in os.listdir(f'./cogs/{folder}/{module}'):
            for filename in os.listdir(f'./cogs/{folder}/{module}/{category}'):
                try:
                    if filename.endswith('.py'):
                        bot.load_extension(f'cogs.{folder}.{module}.{category}.{filename[:-3]}')
                except Exception as e:
                    print(f'Error: {e}')

I wrote this code on my own since I didn´t want to always have multiple functions to run different modules e.g.
events.client.ready, events.guild.memberJoin etc.
In my cogs folder I have 2 folders (and more to come), events & cmds, inside those there are more folders which then lead to a .py file.

The problem is that windows gives me an error that this directory name is not correct. Why is that so?

steep thunder
dusk gale
#

it does not reach the extension load, specific error is at

for filename in os.listdir(f'./cogs/{folder}/{module}/{category}'):
#

ohh

steep thunder
#

If you're planing to load all .py files you could just do
bot.load_extentions('./cogs')

#

os.listdir("cogs/") try this tho

dusk gale
#

this does not load the files

#

the path is correct it is really weird to me

#

it´s a NotADirectoryError

#

and displays the correct path xD

steep thunder
#

Well duh,, haha

#

listdir gives you files

#

os.walk is what you're after

#

[x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively.

#

if you want to use listdir, you need to pair it with os.path.isdir

dusk gale
#

I went back to coding as soon as you said I need os.walk xD

#
def load_cogs():
    for folder, subfolder, file in os.walk("cogs/"):
        for filename in file:
            if filename.endswith(".py"):
                filenamepath = os.path.join(folder, filename)
                filenamepath = filenamepath.replace("\\", ".")
                filenamepath = filenamepath.replace("/", ".")
                filenamepath = filenamepath.replace(".py", "")
                bot.load_extension(filenamepath)

load_cogs()

Does this make sense to you?

#

It does load everything I want now

steep thunder
#

makes sense to me

#

You can string them all after each other tho if you preffer replace().replace().replace() etc

dusk gale
#

yeah that would be good clean up

#

thanks once again strix

steep thunder
#

More of a style preference, im sure some would loose their mind over it

dusk gale
#

definetly xD

steep thunder