Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在断电前写入外部文件_Python 3.x_Pygame_Backup - Fatal编程技术网

Python 3.x 在断电前写入外部文件

Python 3.x 在断电前写入外部文件,python-3.x,pygame,backup,Python 3.x,Pygame,Backup,我有一个在raspberry pi上运行的python记分板程序,我需要它在从停电(我住的地方很常见)回来后恢复上面的信息。以下仅为保存机制的代码: import pygame from pygame.locals import * if os.path.isfile('backup.txt'): print('Reloading details from previous game... ') backup = open('backup.txt', 'r') tim

我有一个在raspberry pi上运行的python记分板程序,我需要它在从停电(我住的地方很常见)回来后恢复上面的信息。以下仅为保存机制的代码:

import pygame
from pygame.locals import *

if os.path.isfile('backup.txt'):
    print('Reloading details from previous game... ')
    backup = open('backup.txt', 'r')

    time_a = float(backup.readline().rstrip('\n'))
    team1name = backup.readline().rstrip('\n').upper()
    team2name = backup.readline().rstrip('\n').upper()
    team1score = int(backup.readline().rstrip('\n'))
    team2score = int(backup.readline().rstrip('\n'))
    currentperiod = int(backup.readline().rstrip('\n'))
    team1fouls = int(backup.readline().rstrip('\n'))
    team2fouls = int(backup.readline().rstrip('\n'))
    possesion = bool(backup.readline().rstrip('\n'))

pygame.time.set_timer(USEREVENT + 1, 100)

while True:  # Main loop
    clock.tick(30)
    for event in pygame.event.get():

        if event.type == USEREVENT + 1:  # Write to backup file
            backup = open('backup.txt', 'w')
            backup.write('{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n'.format(
                str(time_a), team1name, team2name, str(team1score), str(team2score),
                str(currentperiod), str(team1fouls), str(team2fouls), str(possesion)))
            pygame.time.set_timer(USEREVENT + 1, 100)

        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                backup.close()
                os.remove('backup.txt')
                sys.exit()
如果我通过执行
kill-9processid
来模拟断电,然后重新运行程序,没有什么问题。但是如果我通过拔下pi上的插头来模拟断电,
backup.txt
是空的

我已尝试更改保存的频率(
USEREVENT+1


如何让程序在实际断电之前保存到
backup.txt

直接写入磁盘而不是缓冲区解决了这个问题。做:

backup.flush()
os.fsync(backup.fileno())