【问题标题】:File is only written at the end of my program文件只写在我的程序末尾
【发布时间】:2020-05-11 17:28:12
【问题描述】:

我正在使用 pygame 在 Python 中创建一个游戏,当我更新我的 pygame 显示时我必须更新我的文件。 但是当我尝试写它时,它只写在我的程序末尾。

我尝试写入文件的类

class GameReader():

    def __init__(self):

        self.file_content = [
            {'last_edit': 0},
            {
                'map_infos': {
                    'p1': 0,
                    'p2': 0,
                    'p3': 0,
                    'p4': 0,
                    'p5': 0,
                    'p6': 0,
                    'p7': 0,
                    'p8': 5
                }
            }
        ]

        self.update_file()

    def update_file(self):
        with open('gameFiles/game.yaml', 'w') as file:
            yaml.dump(self.file_content, file)
            file.close()

GameReader()的实例存储在一个类Game()

while running:

    # ajout du menu
    screen.blit(game.menu.image, game.menu.rect)

    # ajout du boutton de départ
    screen.blit(game.start_btn.image, game.start_btn.rect)

    # update
    pygame.display.flip()

    # update de la game file
    game.game_reader.update_file()

    # recuperer les events
    for event in pygame.event.get():

        # si fermeture de fenetre
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()

【问题讨论】:

  • 所以你可能需要做 game.update_file()
  • 不管问题是什么,我怀疑您是否真的想要(或需要)在每次显示循环迭代时更新文件。最好只更新内存中的self.file_content 字典,并且只在游戏结束时写入文件。
  • 它只是出现文件在你的程序结束时被更新(它与文件是否被刷新或不是)。该文件已多次更新,但最终结果将——毫不奇怪——是程序结束前发生的最后一次重写。
  • 文件通常不需要刷新,因为它们在关闭时会自动发生。此外,当使用with 打开文件时,它会自动关闭,因此您无需执行其中任何一项操作。我不确定您如何确定上次写入文件的时间,但认为您一定是误认为flush() 解决了正在发生的问题。当然,如果没有minimal reproducible example,我们永远不会知道……

标签: python file while-loop pygame yaml


【解决方案1】:

文件是通过缓冲区写入的,因此您需要刷新它。

file.flush()

【讨论】:

    【解决方案2】:
    def update_file(self):
            with open('gameFiles/game.yaml', 'w') as file:
                yaml.dump(self.file_content, file)
                file.flush()
                file.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2014-02-04
      • 2011-04-14
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多