python-3.x - 读取文件目录,然后在 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 所以有谁知道该怎么做
解决方案
要获取目录中的文件数,您可以这样做(这称为“列表理解”,类似于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
循环之前或发生事件时这样做。
推荐阅读
- robotframework - 如何摆脱机器人固件 Python 中的错误“不存在的设置‘套件设置’”
- html - 如何切换多个浮动右元素的顺序?
- matlab - 如何在 Simulink 中实现时间相关的指数函数
- php - php cron timeout - 在后台运行脚本
- php - 使用 PHP 在 MySql 中上传图片
- jquery - 如果 div 有类删除类或者添加一个新类
- c++ - ESP32 意外重启 - 有问题的变量?
- javascript - 三.JS | GLSL 通过场景纹理设置粒子颜色
- c++ - 在 CMakeLists 中结合 C++ 和 CUDA 时将 CXX-standard 设置为 c++17
- node.js - 如何在graphql中实现分页,它返回分页元数据和数据集