Saving the data with this structure is complicating life unnecessarily when it comes to recovering them. The option to serialize the data that Gerardo proposes is very good if you are only going to read the data with Python. You can create a student class with the appropriate attributes and serialize the instances. Another option is to store them in a dictionary and then serialize it.
However if you have to use a text file it would be best to use a format csv . Student, address and telephone would be the columns:
import csv
headers = ('estudiante', 'direccion', 'telefono')
datos=({'estudiante':'Carlos Rojas', 'direccion':'Alajuela', 'telefono':'2222222'},
{'estudiante':'Luiz Perez', 'direccion':'Heredia', 'telefono':'5555555'})
with open('datos.csv', 'wb') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=headers)
writer.writeheader()
writer.writerows(datos)
The csv or txt (the extension does not really matter) would be:
student, address, telephone number
Carlos Rojas, Alajuela, 2222222
Luiz Perez, Heredia, 8888888
Later we can recover the data analogously:
import csv
with open('datos.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['estudiante'], row['direccion'], row['telefono'],)
With what we get:
('Carlos Rojas', 'Alajuela', '2222222')
('Luiz Perez', 'Heredia', '5555555')
You can add data or modify them easily. To modify data in a text file is usually loaded into memory, modified and then rewritten:
import csv
with open('datos.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
data = [row for row in reader]
for row in data:
if row['estudiante']=='Luiz Perez':
row['telefono']='8888888'
with open('datos.csv', 'wb') as csvfile:
nuevo = {'estudiante':'Laura Aguilera', 'direccion':'Alajuela', 'telefono':'9999999'}
writer = csv.DictWriter(csvfile, fieldnames=reader.fieldnames)
writer.writeheader()
writer.writerows(data)
writer.writerow(nuevo)
With this we change the telefono
of Luiz Peres
and add another student named 'Laura Aguilera'.