Home > Back-end >  How do i save my replacement to the file in python as it will print but when i check in the file it
How do i save my replacement to the file in python as it will print but when i check in the file it

Time:03-04

for line in file:
    if ammend_f and ammend_l in line:
      print(line)
      
      change_sc = int(input("Would you like to change the score for this student?\n1) Yes\n2) No\n--\n"))
      if change_sc == 1:
        #new_score = input("New score: ")
        adjust_array = line.split(",")
        #adjust_array[2] = str(new_score)
        import sys
        import fileinput
 
        #x = input("Enter old score: ")
        x = adjust_array[2]
        print(adjust_array[0] "'s" , "score is" , x)
        y = input("Enter new score: ")
 
        for l in fileinput.input(files = "test_results.csv"):
            l = l.replace(x, y)
            sys.stdout.write(l)
      
      if change_sc == 2:
        print("{No changes made}")

When i run the program, everything works but it wont save my changes to file. the changes will come up and print but when i check back in the file, everything has stayed the same. btw this is only one part of my code

CodePudding user response:

The string l is in memory, and sys.stdout doesn't write back into files.

If you want to replace text in a file, you need to open the file and write all previous and replaced lines back to it

CodePudding user response:

With the code provided, there are issues remaining before writing the file changes.

# Test file
file = open('test1.txt')

for line in file:
    if 'ammend_f' and 'ammend_l' in line: # changed 'ammend_f' and 'ammend_l' to string
        print(line)

        change_sc = int(input(
            "Would you like to change the score for this student?\n1) "
            "Yes\n2) No\n--\n"))
        if change_sc == 1:
            # new_score = input("New score: ")
            adjust_array = line.split(",")
            # adjust_array[2] = str(new_score)
            import sys
            import fileinput

            # x = input("Enter old score: ")
            x = adjust_array[2]
            print(adjust_array[0]   "'s", "score is", x)
            y = input("Enter new score: ")

            for l in fileinput.input(files="test_results.csv"):
                l = l.replace(x, y)
                sys.stdout.write(l)

        if change_sc == 2:
            print("{No changes made}")

Results:

Traceback (most recent call last):
  File "C:\Users\ctynd\OneDrive\CodeBase\StackOverflowActivity\QuestionFiles\Q100_original_Code.py", line 19, in <module>
    x = adjust_array[2]
IndexError: list index out of range
  • Related