import os
import time
ARCHIVO = "fibonacci_log.txt"
# -----------------------------
# Fibonacci iterativo (rápido)
# -----------------------------
def fibonacci_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# -----------------------------
# Fecha y hora formateadas
# -----------------------------
def fecha_hora():
t = time.localtime() # (año, mes, dia, hora, min, seg, wday, yday)
fecha = "{:04d}-{:02d}-{:02d}".format(t[0], t[1], t[2])
hora = "{:02d}:{:02d}:{:02d}".format(t[3], t[4], t[5])
return fecha, hora
# -----------------------------
# Asegura encabezado y obtiene próximo registro
# -----------------------------
def preparar_archivo_y_registro():
try:
os.stat(ARCHIVO)
# Contar líneas para continuar numeración (saltando header)
with open(ARCHIVO, "r") as f:
lineas = f.read().splitlines()
if len(lineas) == 0:
# Archivo vacío
with open(ARCHIVO, "w") as f:
f.write("nreg,fecha,hora,fibonacci\n")
return 1
# Si hay encabezado, nreg arranca en (len(lineas)) porque lineas incluye header
# Ej: header + 3 datos => len=4 => próximo nreg=4
return len(lineas) # funciona si 1ra línea es header
except OSError:
# No existe: crear con header
with open(ARCHIVO, "w") as f:
f.write("nreg,fecha,hora,fibonacci\n")
return 1
# -----------------------------
# Main
# -----------------------------
def main():
N = int(input("Ingrese la longitud de la serie Fibonacci: ").strip())
if N <= 0:
print("N debe ser > 0")
return
nreg = preparar_archivo_y_registro()
with open(ARCHIVO, "a") as f:
for i in range(N):
fib = fibonacci_iter(i)
fecha, hora = fecha_hora()
# formato: numerode registro, fecha, hora, fibonacci
linea = "{} {} {} {}\n".format(nreg, fecha, hora, fib)
f.write(linea)
print(i, fib) # salida en consola (opcional)
nreg += 1
time.sleep_ms(50) # opcional: para ver cambio de hora/seg y no saturar
print("\n Datos guardados en:", ARCHIVO)
# Ejecutar
main()