I am doing a small billing system and when I want to save the data in a .txt
, it is not saved.
from io import open
from datetime import date
import random
fecha = date.today()
numero = random.randrange(1, 1000)
iva = 0.21
print(":::::::: Facturación ::::::::\n")
cliente = input("Cliente: ")
servicio = input("Servicio: ")
precio = int(input("Precio: $"))
subtotal = precio * iva
total = precio + subtotal
craer_factura = open(str(fecha)+str(numero)+".txt", "w")
craer_factura.write('''
"Factura #"+numero
"-------------------"
"Cliente: "+cliente
"Servicio: "+servicio
"-------------------"
"Valor: $"+precio
"IVA 21%: $"+subtotal
"-------------------"
"Total: $"total
''')
print("Total: $"+str(total))
It does not throw me errors, but it saves .txt
the data as it is written and does not take the variables.
I appreciate the help.
You have a problem like this:
You're using triple quotes, which is the easiest way to write multiline strings, the problem is that everything inside the triple quotes evaluates to a single string, so the concatenation we're trying with
El valor de variable es: + variable
is useless.The other problem that you could eventually have, if you solve the previous one, is that the operator
+
works in different ways according to the type of data. For example:The problem is simple, concatenation (the
+
) only works like this if it's two strings, butvariable
it's an integer.An optimal way is to use
F-strings
what you have already been told about, valid for versions 3.6 or higher, in previous and higher versions you can do something similar, using the methodformat()
:Taken your case, it would be something like this:
Python does not automatically replace variables within the string. If you're using Python 3.6 or higher, you can use f-strings to make things easier: