Goal:
I have a file named airplanes.txt. It already contains some of my favourite planes:
Boeing 747
Airbus A380
I am taking an input in my main app in order to add a plane stated by the user into this airplanes.txt file.
Example:
Please type the name of the plane you want to add to your favourites list: <<Boeing 737>>
If you look at the airplanes.txt file now you see:
Boeing 747
Airbus A380
Boeing 737
My question:
My code below works by first getting the existing data in the airplanes.txt.
airplane_file = open('airplanes.txt', 'r')
favourite_airplanes = [ line.strip('\n') for line in airplane_file.readlines()]
airplane_file.close()
Next, I close the file, and then, take a user input.
add_plane = input('Enter The Airplane You Would Like To Add To This List: ')
Finally, I write back all the existing data which was in the file and then add on the user input to that.
if add_plane != None:
reopened_airplane_file = open('airplanes.txt', 'r+')
for airplane in favourite_airplanes:
reopened_airplane_file.write(f'{airplane}\n')
else:
reopened_airplane_file.write(f'{add_plane}\n')
I feel like there should be some way to write data into existing files which contain data without needing to rewrite all the data back into it + new data.
This can become increasingly tedious as, for enormous files, it would take a huge amount to time to write only the existing data back into the file and then write the new data which you would expect to add.
I have tried to make this question as readable as possible by deconstructing my code so I hope you don't mind the long question. :)
Edit:
This worked for me:
with open('airplanes.txt', 'a+') as file:
add_plane = input('Enter The Airplane You Would Like To Add To This List: ')
file.write(f'{add_plane}\n')
Why it wasn't working:
I was using the r+ mode which meant that I was overwriting though a+ mode was the appropriate one to use!
a+ open for reading and appending (writing at end of file). The file is created if it does not exist.