-1

我有这个代码。

# -*- coding: utf-8 -*-
import pickle
import random

guessesTaken = 0

print('Hello! What is your name?')
name = raw_input()
number = random.randint(1, 20)
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')

while guessesTaken < 6:
    print('Take a guess.') # There are four spaces in front of print.
    guess = raw_input()
    guess = int(guess)

    guessesTaken = guessesTaken + 1

    if guess < number:
        print('Your guess is too low.') # There are eight spaces in front of print.

    if guess > number:
        print('Your guess is too high.')

    if guess == number:
        break

if guess == number:
    guessesTaken = str(guessesTaken)
    print('Good job, ' + name + '! You guessed my number in ' + guessesTaken + ' guesses!')


has= str(name) + '    ' + str(guessesTaken)


f='toplevel.data'
f = open(f, 'wb')
pickle.dump(has, f) # depunem (engl. dump) obiectul în fişier
f.close()

我有个问题。如果我再次玩这个“游戏”toplevel.data 将用新文件刷新。我希望如果我再次玩这个游戏 toplevel.data 不会用新文件刷新。我希望新文件放在旧文件之后,例如:旧文件新文件(1)新文件(2)新文件(3)...................... ............... 对不起我的英语不好。

4

2 回答 2

1

如果我正确理解了您的问题,您希望在文件末尾而不是顶部写。

您可以以追加模式打开文件a+或将文件指针设置到末尾,f.seek(-1,2).

于 2012-08-23T07:36:05.847 回答
0

您可以尝试通过计算现有文件来对文件进行编号:

import os, glob

# ...

files = glob.glob('toplevel*.data')
filename = 'toplevel{n}.data'.format(n=len(files))

with open(filename, 'wb') as handle:
  pickle.dump(has, handle) # depunem (engl. dump) obiectul în fişier
于 2012-08-23T07:36:01.857 回答