help txt files in python

0

Good evening

Veran I am new to python and I need someone to explain to me how to do save an information x in txt file for example:

student: carlos rojas age: 29 Address: alajuela telefo: 2222222

student: luis perez age: 18 Address: heredia telephone: 5555555

to then search it in the same txt and if necessary modify  some in specific or delete it I appreciate any help you give me

    
asked by Luis David Jimenez 07.04.2017 в 05:48
source

3 answers

1

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'.

    
answered by 07.04.2017 в 11:16
0

You can use the pickle module to save an entire object in a binary file

pickle.dump(obj, file, pickle.HIGHEST_PROTOCOL)

and to read each object you would use

obj = pickle.load(file)

This way you can load object by object saved in the file and check if it is what you are looking for for example

if obj.nombre = "nombre":
     # dejas de buscar y procesas la informacion
else:
     #sigues cargando el sig. obj hasta que llegues al final del archivo judicial
    
answered by 07.04.2017 в 09:07
0

You can create a file that has the lines separated with semicolons as in example:

data = [line.split(';') for line in open('archivo.txt').read().splitlines()]
    
answered by 07.04.2017 в 21:31