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.

101, Jane Doe, 1978
102, John Doe, 1907

with open('patients.txt', 'a+') as f:
    id = int(input('Enter patient ID: '))
    name = input('Enter patient name: ')
    yob = input('Enter patient year of birth: ')

    f.write('str(id) + ',' + name + ',' + yob)

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:

with open(ur_file, 'r+') as f:
    id = max(int(line.split(', ')[0]) for line in f)+1  # SHOULD use csv module
    print(f'new patient id: {id}')
    name = input('Enter patient name: ')
    yob = input('Enter patient year of birth: ')

    # pointer is now at the end - just write the data...
    
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement