Python:读写带有“r+b”的.rps文件

2024-05-23 20:52:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个石头,布,剪刀的游戏,需要用户输入,玩游戏对电脑,并保存结果。你知道吗

用户将显示一个选择列表,最后一个选择是退出游戏,然后将他们的胜负和联系保存到一个.rps文件中。在实际的游戏中,您可以查看统计数据,因此当您退出游戏时,我使用pickle dump将它们添加到文件中。.rps文件输出应如下所示:

user_name
wins:
losses:
ties:

本节的代码是:

try:
    user = self.name
    rps = ('.rps')
    file = user + rps
    save_file = open(file, 'r+b')
    pickle.dump(user, save_file)
    user_wins = self.wins
    pickle.dump(user_wins, save_file)
    user_losses = self.losses
    pickle.dump(user_losses, save_file)
    user_ties = self.ties
    pickle.dump(user_ties, save_file)
    save_file.close()
    print(self.name, ' , your game has been saved.', sep='')
    self.play = False

except Exception as err:
    print('Sorry ', self.name, ', the game could not be saved.')
    print(err)
    self.play = False

我使用类进行练习,所以这只是代码的一部分,但这是唯一不起作用的部分。每次尝试退出程序并保存结果时,都会出现“不存在这样的文件或目录”错误。我已经测试了路径,以确保它应该在正确的目录中创建文件,它是,但我不知道为什么它不创建文件,如果它还不存在。我以为用r+b就是这么做的?你知道吗


Tags: 文件用户nameself游戏savedumppickle
1条回答
网友
1楼 · 发布于 2024-05-23 20:52:10

你想用a+b,而不是r+b

rb+

Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.

ab+

Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

资料来源:http://www.tutorialspoint.com/python/python_files_io.htm

请注意,如果文件中已有任何文本,则文件指针将位于文件末尾。如果要使用rb+打开文件,请首先使用helper方法检查文件是否存在,如果文件不存在,请创建它。你知道吗

def createFileIfNotExists(filePath):
     open(filePath, 'ab+')
     close(filePath)
     return

注意我的功能是低效的,我建议你寻找一个更优雅的解决方案,如果你想走这条路。你知道吗

相关问题 更多 >