设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: mty1111
打印 上一主题 下一主题

【Python 第41课】 用文件保存游戏(3)

[复制链接]

0

主题

0

好友

50

积分

注册会员

Rank: 2

楼主
发表于 2015-11-5 10:35:08 |显示全部楼层
请教下,game1.txt中原来有两条记录,但是只要加上最后一段的写文件(f.write),game1.txt就被清空了,一片空白,原来的记录没有了。哪里出问题了?(python3.3;PyScripter V2.6 x86). 谢谢~
from random import randint
name = input('Input Your Name:')
f = open('C:\Documents and Settings\Administrator\My Documents\game1.txt')
lines = f.readlines()
#print (lines)
f.close()
scores = {}
for l in lines:
#    print(l)
    s = l.split()
#    print (s)
    scores[s[0]] = s[1:]
#    print (scores)

score = scores.get(name)
#print(score)
if score is None:
    score = [0,0,0]

game_times = int(score[0]) + 1
min_times = int(score[1]) + 2
total_times = int(score[2]) + 3
if game_times > 0:
    avg_times = float(total_times) / game_times
else:
    avg_times = 0

print ('%s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案' % (
    name, game_times, min_times, avg_times))

num = randint(1,100)
times = 0 #记录本次游戏轮数
print ('Guess what i think')

scores[name] = [str(game_times), str(min_times), str(total_times)]
#print(scores[name])
#print(scores)
result = ''
for n in scores:
    line = n + ' ' + ' '.join(scores[n]) + '\n'
#    print(n)
#    print(scores[n])
#    print (' '.join(scores[n]))
    result += line
#    print (line)
#    print(result)
print (result)

f = open('C:\Documents and Settings\Administrator\My Documents\game1.txt','w')
f.write (result)
#print(result)
f.close

回复

使用道具 举报

0

主题

0

好友

50

积分

注册会员

Rank: 2

沙发
发表于 2015-11-6 10:01:03 |显示全部楼层
crossin先生 发表于 2015-11-5 16:27
你去看下 open的打开模式
'w'模式就是重新写文件

'w'的确是重写,改成‘a’就不清空了,但是问题不在这里。而是不管w还是a,数据都没有写进到文件里面。
比如,print (result),在屏幕上显示的是:
czy 4 5 6
cy 1 2 3
xxm 1 2 3
想要写到文件里:f = open('C:\Documents and Settings\Administrator\My Documents\game1.txt','a')
                        f.write (result)
再次打开文件,显示的还是:
czy 4 5 6
cy 1 2 3
完全没有变化!为什么数据没有被写进文件呢?
回复

使用道具 举报

0

主题

0

好友

50

积分

注册会员

Rank: 2

板凳
发表于 2015-11-9 09:38:50 |显示全部楼层
crossin先生 发表于 2015-11-6 21:18
你没有close,你那个close没有加括号,就不是调用方法

的确是这样,修改后就正常了。原来怎么也想不明白,还以为是版本问题。原来写文件时一定要关闭,拿掉f.close()也不行。非常感谢~。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-17 10:32 , Processed in 0.030106 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部