覆盖文件python中的标志

时间:2014-07-08 16:25:08

标签: python

我有一个以下格式的文件:

[character1]    
health = 100    
lives = 3        
some other flags

[character2]    
health = 50    
lives = 1    
etc

[character3]    
missing lives line    
some other flags

我以这种格式获得有关更新生活的信息: lives[char][status] character1的位置lives['character1']['lives = 3']

所以我要做的就是浏览文件并根据上面的信息更新生命,并添加遗失的生命标志,例如character3

with open('characters.txt', 'rw') as chars:
    for line in chars:
        if line.find('[') is not None:
            character = line
        if line.find('lives =') is not None:
            if line != lives[character][status]
                line = line.replace(lives[character][status])
            chars.write(line)

这是我背后的一般逻辑,但看起来字符被设置为跟随它的行(health = 100

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

我强烈建议您将字符数据存储在字典中,然后将它们导出/导入为JSON。这将为您节省很多麻烦。

例如,存储您的角色:

data = {'character1':{'lives':3, 'health':100}, 'character2':{'lives':4, 'health':85}}

您可以将内容写入如下文件:

import json
with open('myfile', 'w') as f:
    f.write(json.dumps(data))

您可以从文件中加载这样的播放器数据:

import json
with open('myfile', 'r') as f:
    data = json.load(f)

现在改变一个角色的统计数据是微不足道的。例如,character2的健康状况降至50:

data['character2']['health'] = 50

或者角色1死了:

if data['character1']['health'] <= 0:        
    data['character1']['lives'] -= 1     

完成更改后,请使用datajson.dumps写回文件。

答案 1 :(得分:2)

您应该使用内置ConfigParser module。它将直接处理这个问题:

>>> i = '''[character1]
... health = 100
... lives = 3
...
... [character2]
... health = 50
... lives = 1
...
... [character3]
... lives = 2
... '''
>>> import ConfigParser
>>> import io
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(io.BytesIO(i))
>>> config.get('character3', 'lives')
'2'

要从文件中读取,它更简单:

>>> config = ConfigParser.ConfigParser()
>>> config.readfp(open('some-file.txt'))
>>> config.get('character3', 'lives')

进行更改并写出文件:

>>> config.set('character3', 'lives', '4')
>>> config.write(open('foo.txt','w'))
>>> config.readfp(open('foo.txt')) # Read the file again
>>> config.get('character3','lives') # Confirm the new value
'4'