0

I have a file that includes student IDs and their scores. I'm trying to create a file with the name usoscorelist.txt and write the inside of the scorelist.txt in it, changing the score of the student 151133 from 40 to 100. I think the space between the ID and the score is making a problem here. I'm not getting any errors nor seeing any changes in the file.

with open('scorelist.txt','r') as firstfile, open('usoscorelist.txt','r+') as secondfile:
    for line in firstfile:
        secondfile.write(line)
    for line in secondfile:
        print(line.replace(151133 + " " + 40, 151133 + " " + 100))
secondfile.close()

The inside of scorelist.txt is:

121787 74
121367 71
121817 88
121619 85
131445 80
131244 96
131872 98
131963 75
131172 78
131965 72
131112 90
131956 87
141105 61
141703 61
141407 78
141569 82
141585 89
141455 82
141370 80
141837 67
141857 86
141497 94
141853 67
141245 80
151452 83
151238 62
151827 58
151409 40
151789 95
151742 71
151133 40
151095 49
151186 75
151586 51
151926 73
151975 96
151079 49
151091 100
151588 49
151630 61
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
HAZEM
  • 29
  • 7
  • I think the data is getting appended as a `str` (string) type, so if you only want to replace the value of `student_id == 151133`, you can try `line.replace("151133 40", "151133 100")` instead. – Gautam Chettiar Oct 10 '22 at 05:39
  • You are writing the line unchanged. You need to check the line has the student id then use .replace before writing it. The print statement can be omitted. – user19077881 Oct 10 '22 at 05:44
  • "I'm not getting any errors nor seeing any changes in the file." Yes, you are. `151133 + " " + 40` will cause `TypeError`. – Karl Knechtel Oct 10 '22 at 06:09

1 Answers1

1

edit the line before writing it, if you replace the line after writing it, you are just changing the line in the program but not the file

for the spaces between the id, you can either just use string as id, or use a f-string (format string)

tips: you dont need to close the file when using with, it will handle it for you

with open('scorelist.txt','r') as firstfile, open('usoscorelist.txt','w+') as secondfile:
    student_id = 151133
    original_score = 40
    new_score = 100
    original_str = f"{student_id} {original_score}"
    new_str = f"{student_id} {new_score}"

    for line in firstfile:
        secondfile.write(line.replace(original_str, new_str))

#checking
with open('usoscorelist.txt', 'r') as secondfile:
    for line in secondfile:
        print(line,end='')
Electron X
  • 330
  • 1
  • 10
  • @HAZEM It gives me exactly 40 on my device, the exact same code. I think i know the reason, the second file is not empty and have more than 40 lines originally. so when you write using `r+` flag it wont overwrite the extra lines that already existed. use `w+` flag for second file to solve this problem – Electron X Oct 10 '22 at 05:56