0

The data file I am working with takes the format:

6345 Alfonso Chavez 98745.35 
2315 Terry Kulakowski 234.0 
4455 Yu Chen 78000.0 

What I am trying to do is replace the balance(the last item in the line) with an updated balance which I have generated in my code. I'm not sure how to do this with an existing file without wiping the entire thing first, which is obviously not what I want. I was thinking a for loop to iterate over the line and split it into separate list elements, but that will update every users balance instead of the specific persons. Any help is appreciated.

Droxbot
  • 53
  • 1
  • 10

1 Answers1

1

If this is a text file, there is no great way of doing this. In general it's probably impossible/super hard to save changes in a text file without saving/rewriting the whole text file. Instead, what you should be focusing on is the fact that you need O(n) time to loop through the entire file looking for the specific person.

Having said all that, python module fileinput seems like a good way to do this. See this. You can set inplace=True to make it seem like you are just changing that single line in place.

But this is still O(n). It's just secretly rewriting the whole file for you behind your back.

Also some other solutions discussed here previously.

Community
  • 1
  • 1
conrad
  • 1,783
  • 14
  • 28
  • obviously the best solution would be to not keep the data in a text file, but in a database instead. failing that, maybe you could keep the data in a python dict and just pickle or shelve it instead. then you would be able to update balance in O(1) time. – conrad Nov 05 '14 at 04:02
  • Thank you. I will look into the links you provided. – Droxbot Nov 05 '14 at 06:24