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
x
10
10
1
101, Jane Doe, 1978
2
102, John Doe, 1907
3
4
with open('patients.txt', 'a+') as f:
5
id = int(input('Enter patient ID: '))
6
name = input('Enter patient name: ')
7
yob = input('Enter patient year of birth: ')
8
9
f.write('str(id) + ',' + name + ',' + yob)
10
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
1
9
1
with open(ur_file, 'r+') as f:
2
id = max(int(line.split(', ')[0]) for line in f)+1 # SHOULD use csv module
3
print(f'new patient id: {id}')
4
name = input('Enter patient name: ')
5
yob = input('Enter patient year of birth: ')
6
7
# pointer is now at the end - just write the data...
8
9