首页 > 解决方案 > 读取文件目录,然后在 pygame 表面上显示它们

问题描述

我有一个函数可以读取一个名为“游戏”的目录并在其中查找某些文件。这部分工作正常。问题是我想计算有多少文件,并且对于每个文件我想将 10 添加到变量中。

def games():
    f = 0
    sy = 100
    ftext = pygame.font.SysFont("Arial", 20)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        screen.fill(DarkSpace)
        ToolBarButton("Home", 0, 0, 150, 50, SpaceGrey, CornflowerBlue, 10, cmain)
        ToolBarButton(username, 153,0,150,50, SpaceGrey, CornflowerBlue, 10, accountDetails)
        ToolBarButton("Programs", 305,0,150,50, SpaceGrey, CornflowerBlue, 10, programs)
        ToolBarButton("Games", 458,0,150,50, SpaceGrey, CornflowerBlue, 10, games)
        ToolBarButton("Help", 610,0,150,50, SpaceGrey, CornflowerBlue, 10, hel)
        DropDown(NeonGreen, CornflowerBlue, 764, 16, 30, 30, DropMenu)
        Btext(screen, "Loading Games!", CornflowerBlue, ftext, 600,600,600,600)
        fileDir = os.listdir(r"D:\Users\26099\Desktop\Programming\Dark_Dragons\Blunt_Wars1\venv\Launcher\Games")
        nf = len(fileDir)
        while nf > f:
            f += 1
            sy += 10
            break
        print(sy)
        for fileN in fileDir:
            verif = fileN.endswith('.py') or fileN.endswith('.pyw')
            if not verif:
                fileDir.remove(fileN)
            else:
                print(fileN)
                text(screen, fileN, CornflowerBlue, ftext, 300,sy)
        pygame.display.update()

所以我想为每个具有特定扩展名的文件添加 100 到 sy。我尝试将其放入 for 循环中,但出现错误说 int object is not callable 所以有谁知道该怎么做

标签: python-3.xfilevariablespygame

解决方案


要获取目录中的文件数,您可以这样做(这称为“列表理解”,类似于for将文件附加到空列表的循环):

files = [f for f in os.listdir() if os.path.isfile(f)]
num_files = len(files)

如果你想计算特定的扩展,你可以这样做(最好使用字典而不是单独的变量):

py_files = 0
pyw_files = 0
for file_name in os.listdir():
    if file_name.endswith('.py'):
        py_files += 1
    elif file_name.endswith('.pyw'):
        pyw_files += 1

或者以更复杂的方式使用collections.Counter

import collections

extensions = collections.Counter(
    os.path.splitext(f)[1] for f in os.listdir() if os.path.isfile(f))
print(extensions, sum(extensions.values()))

补充说明:

不要在迭代列表时修改列表。这会导致意想不到的结果。而是创建一个新的过滤列表。

while nf > f:循环看起来毫无意义。你可以nf乘以10: sy = nf * 10。此外,因为您调用break,所以您在第一次迭代后结束循环。

您可能不必每帧重新计算文件,每秒数百次,所以我会在while循环之前或发生事件时这样做。


推荐阅读