Skip to content
Advertisement

Auto-increment number in a text file

I have a text file with some patient information. I want to add a new patient into the file while incrementing the id automatically.

JavaScript

How can I check the last id number in the file and increment it based on that?

Advertisement

Answer

Open the file in r+ so that the file pointer is at the beginning vs at the end of the file.

Then use max()+1 for the new id. The comprehension used in max() reads the whole file, calculated the max, and leaves the file pointer at the end:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement