Metniniz yalnızca bir kişi içeriyorsa:
import re
with open('pers.txt','wb') as g:
g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 ')
with open('pers.txt','rb') as h:
print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt before treatment:\n',h.read()
def roplo(file_name,what):
patR = re.compile('^([^\r\n]+[\r\n]+)[^\r\n]+')
with open(file_name,'rb+') as f:
ch = f.read()
f.seek(0)
f.write(patR.sub('\\1'+what,ch))
roplo('pers.txt','Mage')
with open('pers.txt','rb') as h:
print '\nexact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt after treatment:\n',h.read()
Metniniz birkaç kişi içeriyorsa:
yeniden ithal
with open('pers.txt','wb') as g:
g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 \n Jim \n dragonfly\r300\r2\n10\r\nSomo\ncosmonaut\n490\r\n3\r65')
with open('pers.txt','rb') as h:
print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt before treatment:\n',h.read()
def ripli(file_name,who,what):
with open(file_name,'rb+') as f:
ch = f.read()
x,y = re.search('^\s*'+who+'\s*[\r\n]+([^\r\n]+)',ch,re.MULTILINE).span(1)
f.seek(x)
f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')
with open('pers.txt','rb') as h:
print 'exact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt after treatment:\n',h.read()
Bir bireyin "işi" metinde sabit uzunlukta olsaydı, metnin yalnızca "işe" karşılık gelen kısmını, istenen kişiye değiştirebilirsiniz: bu, göndereninkiyle aynı fikirdir.
Ama bana göre, bireylerin özelliklerini cPickle dosyasında kaydedilmiş bir sözlüğe koymak daha iyi olur:
from cPickle import dump, load
with open('cards','wb') as f:
dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)
with open('cards','rb') as g:
id_cards = load(g)
print 'id_cards before change==',id_cards
id_cards['Jim'][0] = 'Wizard'
with open('cards','w') as h:
dump(id_cards,h)
with open('cards') as e:
id_cards = load(e)
print '\nid_cards after change==',id_cards