Raspberry Pi
Tutorial de Rapberry Pi en español.
- Juan Antonio Villalpando -
Volver al índice del tutorial
____________________________
6D.- Escritura y lectura de archivos.
- Para escribir y leer contenido de archivo utilizamos el siguiente código:
|
# Escribir en archivo.
f = open ('mi_archivo.txt','w')
f.write('Escritura de archivo.')
f.close()
# Leer archivo.
f = open ('mi_archivo.txt','r')
lectura = f.read()
print(lectura)
f.close()
print("---------")
# Anexar en archivo.
f = open ('mi_archivo.txt','a')
f.write('\n' + 'Otra línea.')
f.close()
# Leer archivo.
f = open ('mi_archivo.txt','r')
lectura = f.read()
print(lectura)
f.close()
|
- w, escribe borrando lo que anteriormente estuviera escrito.
- a, anexar, escribe a continuación de lo que ya estuviera escrito.
- r, lee.
- \n, escribe en la siguiente línea.
___________________________________________
___________________________________________
___________________________________________
2.- Escribir clave en un archivo. Mostrar la clave guardada. Comprobar la clave guardada, si es "123" parpadeará un LED.
- Pulsamos la tecla "1", entraremos en el script "escribe_clave.py" y deberemos escribir una clave numérica con el teclado. Esa clave se guardará en el archivo: clave.txt
- Pulsamos la tecla "2". Se mostrará la clave mediante un print y en la pantalla LCD.
- Pulsamos la tecla "3". Si la clave es "123" parpadeará el LED 37.
- Pulsamos la tecla "4" se apagará el LED 37.
|
# Juan Antonio Villalpando
# kio4.com
#!/usr/bin/env python
import smbus
import sys
import time
import I2C_LCD_driver
import subprocess
import os
class MyKeyboard:
#Modificado por Juan A. Villalpando http://kio4.com
KeyPadTable= [['D','C','B','A'] , ['#','9','6','3'], ['0','8','5','2'], ['*','7','4','1']]
RowID=[0,0,0,0,0,0,0,4,0,0,0,3,0,2,1,0]
CurrentKey=None
def __init__(self,I2CBus=1, I2CAddress=0x20):
self.I2CAddress = I2CAddress
self.I2CBus = I2CBus
self.bus = smbus.SMBus(self.I2CBus)
self.bus.write_byte(self.I2CAddress,0xff)
def ReadRawKey(self):
OutPin= 0x10
for Column in range(4):
self.bus.write_byte(self.I2CAddress,~OutPin)
key = self.RowID[self.bus.read_byte(self.I2CAddress) & 0x0f]
if key >0 :
return self.KeyPadTable[key-1][Column]
OutPin = OutPin * 2
return None
def ReadKey(self):
LastKey= self.CurrentKey;
while True:
NewKey= self.ReadRawKey()
if NewKey != LastKey:
time.sleep(0.01)
LastKey= NewKey
else:
break
if LastKey==self.CurrentKey:
return None
self.CurrentKey=LastKey
return self.CurrentKey
if __name__ == "__main__":
test = MyKeyboard()
mylcd = I2C_LCD_driver.lcd()
todo = ""
while True:
V = test.ReadKey()
if V != None:
todo = todo + V
mylcd.lcd_clear()
mylcd.lcd_display_string(todo, 1)
if V == '#':
sys.stdout.write(todo)
mylcd.lcd_display_string(todo[:-1], 1)
#print(V)
if todo[:-1] == '1':
p1 = subprocess.Popen(['python3','escribe_clave.py'])
print("Pulsado 1")
if todo[:-1] == '2':
p2 = subprocess.Popen(['python3','muestra_clave.py'])
print("Pulsado 2")
if todo[:-1] == '3':
p3 = subprocess.Popen(['python3','comprueba_clave.py'])
print("Pulsado 3")
if todo[:-1] == '4':
os.system("pkill -f 'python3 comprueba_clave.py' ")
print("Pulsado 4")
todo = ""
else:
time.sleep(0.001)
|
|
# Juan Antonio Villalpando
# kio4.com
#!/usr/bin/env python
import smbus
import sys
import time
import I2C_LCD_driver
import subprocess
import os
class MyKeyboard:
#Modificado por Juan A. Villalpando http://kio4.com
KeyPadTable= [['D','C','B','A'] , ['#','9','6','3'], ['0','8','5','2'], ['*','7','4','1']]
RowID=[0,0,0,0,0,0,0,4,0,0,0,3,0,2,1,0]
CurrentKey=None
def __init__(self,I2CBus=1, I2CAddress=0x20):
self.I2CAddress = I2CAddress
self.I2CBus = I2CBus
self.bus = smbus.SMBus(self.I2CBus)
self.bus.write_byte(self.I2CAddress,0xff)
def ReadRawKey(self):
OutPin= 0x10
for Column in range(4):
self.bus.write_byte(self.I2CAddress,~OutPin)
key = self.RowID[self.bus.read_byte(self.I2CAddress) & 0x0f]
if key >0 :
return self.KeyPadTable[key-1][Column]
OutPin = OutPin * 2
return None
def ReadKey(self):
LastKey= self.CurrentKey;
while True:
NewKey= self.ReadRawKey()
if NewKey != LastKey:
time.sleep(0.01)
LastKey= NewKey
else:
break
if LastKey==self.CurrentKey:
return None
self.CurrentKey=LastKey
return self.CurrentKey
if __name__ == "__main__":
test = MyKeyboard()
mylcd = I2C_LCD_driver.lcd()
todo = ""
while True:
V = test.ReadKey()
if V != None:
todo = todo + V
mylcd.lcd_clear()
mylcd.lcd_display_string(todo, 1)
if V == '#':
sys.stdout.write(todo)
mylcd.lcd_display_string(todo[:-1], 1)
# Guarda la clave en un archivo.
f = open ('clave.txt','w')
f.write(todo[:-1])
f.close()
os.system("pkill -f 'python3 escribe_clave.py' ")
sys.stdout.flush()
todo = ""
else:
time.sleep(0.001)
|
|
# Juan Antonio Villalpando
# kio4.com
#!/usr/bin/env python
import smbus
import sys
import time
import I2C_LCD_driver
import os
# Leer archivo.
f = open ('clave.txt','r')
lectura = f.read()
print(lectura)
f.close()
mylcd = I2C_LCD_driver.lcd()
mylcd.lcd_clear()
mylcd.lcd_display_string(lectura, 1)
time.sleep(0.5)
os.system("pkill -f 'python3 muestra_clave.py' ")
|
|
# Juan Antonio Villalpando
# kio4.com
#!/usr/bin/env python
import smbus
import sys
import I2C_LCD_driver
import os
import RPi.GPIO as GPIO # Librería para GPIO
from time import sleep # Función sleep del módulo time
GPIO.setwarnings(False) # Ignorar avisos.
GPIO.setmode(GPIO.BOARD) # Modo de patillaje físico
GPIO.setup(37, GPIO.OUT, initial=GPIO.LOW)
# Leer archivo.
f = open ('clave.txt','r')
lectura = f.read()
print(lectura)
f.close()
mylcd = I2C_LCD_driver.lcd()
mylcd.lcd_clear()
mylcd.lcd_display_string(lectura, 1)
sleep(0.5)
lectura = str(123)
if lectura == '123':
while True:
GPIO.output(37, GPIO.HIGH)
print("Encendido_1.")
sleep(0.5)
GPIO.output(37, GPIO.LOW)
print("Apagado_1.")
sleep(0.5)
|
___________________________________________________
|