0

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?

Mikey
  • 19
  • 1
  • 4

2 Answers2

0

The most obvious approach would be to (1) open the file, (2) read the data into some kind of data structure (maybe a dictionary or a list), (3) interrogate the data structure to get the next id number, (4) update the data structure with the new data, and (5) write the data structure back to the file. You might need to handle the case if more than one instance of your application might trying to access the file at the same time.

Nicholas Hunter
  • 1,791
  • 1
  • 11
  • 14
0

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...
    
dawg
  • 98,345
  • 23
  • 131
  • 206