簡體   English   中英

覆蓋文件python中的標志

[英]Overwrite flags in a file 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

任何幫助將不勝感激!

我強烈建議您將字符數據存儲在字典中,並將其作為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

或character1去世:

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

完成更改后,請使用json.dumpsdata寫回到文件中。

您應該使用內置的ConfigParser模塊 它將直接處理此問題:

>>> 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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM