Home > Blockchain >  Replace value in text file Python
Replace value in text file Python

Time:04-14

I want to check value of score in Text file and if Value of score for given name is less than new score than update it.
I have following text file:

Harry White,8
William Ross,9
Ron Weasley,10

Now, I have following function:

def set_score(name,score):
    s = open('sc.txt','r ')
    scorelist = s.readlines()
    present=False
    for i in scorelist:
        check  = i.split(',')[0]       
        
        if(check==name):
            present=True
            score1= i.rstrip('\n').split(',')[1]
            if(score1<score):
                
                i.replace(score,score1)
            break;
    
    if(present==False):
        s.write(name "," score)
                
            
    s.close()
    
set_score("William Ross","10")

It does not update the value. Why?
I checked, the if condition is run but the replace statement doesn't work.

CodePudding user response:

Not necessarily most efficient but perhaps clearer.

Open the file for reading and load its contents into a dictionary.

If the name exists in the dictionary, compare the scores. If the new score is greater than the old score, update the dictionary.

Open the file for writing and dump the updated dictionary's contents to it.

FILENAME='sc.txt'

def set_score(name, score):
    d = dict()
    with open(FILENAME) as sf:
        for line in map(str.strip, sf):
            ns, cs = line.split(',')
            d[ns] = int(cs)
    if (old_score := d.get(name)) is None or old_score < score:
        d[name] = score
        with open(FILENAME, 'w') as sf:
            for k, v in d.items():
                print(f'{k},{v}', file=sf)

set_score('William Ross', 10)

Note that the file is only re-opened (for writing) if a change is necessary

EDIT:

From a comment elsewhere it seems that if the name does not exist in the file then it should be added. Logic changed accordingly

CodePudding user response:

Because the name is already present in the file, and your code only writes when it isn't.

If you want to change the file when the name is present, you'll need to write to the file in that case as well (changing the string won't affect the file, as you have found).

CodePudding user response:

You cannot change the iterator itself, but that's what you are doing:

for i in scorelist:
(...)           
                i.replace(score, score1)

Try with this:

for ix, i in enumerate(scorelist):
(...)           
                scorelist[ix].replace(score, score1)
  • Related