Python 排除子文件夹和文件

Python 排除子文件夹和文件,python,python-3.x,Python,Python 3.x,我在排除文件和子文件夹方面有点问题 for x in os.walk('core'): for y in glob.glob(os.path.join(x[0], '*.py')): s = y.replace('\\', '.') x = s.replace('.py', '') cogs.append(x) 我的代码用于从每个文件夹中获取所有文件,现在我只想排除文件\uuuu init\uuuuu,模型和子文件夹迁移以及0002\u auto等文件?现在我只是手

我在排除文件和子文件夹方面有点问题

for x in os.walk('core'):
  for y in glob.glob(os.path.join(x[0], '*.py')):
    s = y.replace('\\', '.')
    x = s.replace('.py', '')
    cogs.append(x)
我的代码用于从每个文件夹中获取所有文件,现在我只想排除文件
\uuuu init\uuuuu
模型
和子文件夹
迁移
以及
0002\u auto
等文件?现在我只是手动将其从列表中删除,如:

cogs.remove('core.rpg.models')
cogs.remove('core.rpg.__init__')
cogs.remove('core.rpg.migrations.__init__')

通常您会对os.walk('core')中的root、dir和文件执行
。。操作
dirs
文件
,并将它们与
根目录
组合,以获得它们的完整路径

在顶部使用
glob
类似于对
x[2]
(又称
文件
——它是
根目录中的文件列表)


这将需要更多的切片,以仅包括起始目录(“核心”)而不是它的完整路径。

是否只想列出特定目录的文件。如果是这样,您可以使用此方法导入os print(os.listdir('/path/to/folder/to/list'))…如果没有,请澄清您的问题一位我的主文件夹是
core
,上面的代码从子文件夹路径添加到列表到文件,cogs打印看起来像
['core.\uu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu'、'core.admin.admin.purge'、'core.fun.gameinfos'、'core.fun.gameinfos'、'core.fun.games.games'、'otherfuncommands'、'core.rpg.rpg
诸如此类,因为它将脚本加载到discordbot,但您可以看到它添加了
\uuuu init\uuuu
等文件,并添加了包含
core.rpg.migrations等文件的子文件夹。\uuuuu init\uuuu
我只希望有
core.rpg.script
中的文件,但没有子文件夹,也没有一些文件它工作得很好。非常感谢。
import os

what_i_want = []
skip_files = {"__init__.py"}    

for root, dirs, files in os.walk('core'):
    for f in files:
        # skipe the subdirs models and migrations
        if root.endswith("models") or root.endswith("migrations"):
            continue
        # skip any non .py file
        if not f.endswith(".py"):
            continue
        # skip ceratain .py files
        if f in skip_files:
            continue
        # remove .py from filename
        f = f[:-3]

        # add filename including full root and subst \ to .
        what_i_want.append(os.path.join(root,f).replace("\\","."))