0

PYTHON 3.4 i want to save to line 21 but it instead saves to line 1 same for when i save to line 22

 if event == 'Event 1' and indivcombo == 'Individual 1': 
        with open("data/tournamentdatae1.txt",'r+') as f:
            for i,line in enumerate(get_all,1):         
                if i == 21:
                    individualmain = individual.get() 
                    f.writelines(individualmain)
                    f.writelines("\n")
  • Possible duplicate of [Editing specific line in text file in python](https://stackoverflow.com/questions/4719438/editing-specific-line-in-text-file-in-python) – Shivam Singh May 29 '18 at 10:52
  • no he is asking to swap out data in a file by using specific things in the file where im choosing specific lines and saving on to them so........ plus i likely just made a mistake and can't spot it as this should work as i did this before and it worked. – Jack i chan May 29 '18 at 10:56
  • help don't hate – Jack i chan May 29 '18 at 10:57
  • See this answer to the same question (Method 1 part): https://stackoverflow.com/a/39676548/5371551 – Shivam Singh May 29 '18 at 11:00
  • that is what im doing but its not working see my problem??? – Jack i chan May 29 '18 at 11:05

1 Answers1

0

Make sure that you are closing and reopening the file after calculating get_all, and that you have a else to write the remaining lines

with open("data/tournamentdatae1.txt",'r+') as f:
    get_all=f.readlines()
with open("data/tournamentdatae1.txt",'r+') as f:
    for i,line in enumerate(get_all,1):      
        if i == 21:
            individualmain = individual.get() 
            f.writelines(individualmain)
            f.writelines("\n")
        else:
            f.writelines(line)
Shivam Singh
  • 1,584
  • 1
  • 10
  • 9