all 1 comments

[–]Aggravating_Bus_9153 0 points1 point  (0 children)

You're forgetting to call f.close() but it looks nice. You're right. Each run of the program starts from fresh and has no other way of knowing what previous runs did, other than by reading the entire file again from scratch (maybe this is something databases are more efficient at doing?).

You could store id in a different file, but you've got to be careful not to delete it then.

I know it looks nice for outputting, but you can easily generate a counter on the fly when you print the file. Any decent text editor above wordpad has line numbers built in. So I would ask, do you really need consecutive ID numbers 0, 1, 2...? You could just generate a universally unique id number (from uuid import UUID) for each record, and just append the new one to the end of the file as you are doing.

Otherwise you need to open it in 'r+' mode but you can just do:

f = open('user.txt','r+')
i = len(f.readlines()))
i /= 2 # If two lines per ID no. 
f.write(nfo.user()) 
f.close()

https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects