Ir al contenido principal

Python para escribir archivos en el sistema de archivos

Recientemente me contactó un amigo que programa en Java, y resulta que está haciendo algún tipo de integración en un sistema donde hace su residencia y me pidió un ejemplo sobre cómo generar archivos en texto plano con python. Aquí el ejemplo:

params = {
"foo": "This is a string",
"bar": 200
}

filename = 'texto_python.txt'
file_to_write = open(filename,'w')
file_to_write.write('El contenido del archivo es: {0} y esto un número {1} \n'.format(params["foo"], params["bar"]))
file_to_write.write('Más texto.')
file_to_write.close()

Es un ejercicio básico pero siempre necesario.

Ver en repo https://github.com/jonanx779/python-stuffs/blob/master/writing_file.py

Comentarios

Entradas populares de este blog

Cómo extraer una columna específica de un archivo CSV

Recientemente me encontré con un pequeño reto, simple pero súper útil cuando no quieres complicarte la vida. Necesitaba de una serie de archivos en formato CSV, separados por comas, extraer únicamente las primeras 3 columnas de 4, ¡sí!, pocas columnas, pero con cientos de filas que no estaba dispuesto a editar a mano, y descubrí el comando cut, lo utilicé de la siguiente manera: [jonas]$ cut -d "," -f1-3 origen.csv > destino.csv Donde -d hace referencia al delimitado en el el archivo, -f1-3 hace referencia a las columnas que vamos a extraer, de la número 1 a la 3, origen.csv hace referencia al archivo de original sobre el cuál vamos a tomar las columnas que necesitamos y finalmente destino.csv que es el archivo destino que almacenará el nuevo resultado, y listo!, podrías complicarte la vida con awk , pero si no eres tan experto, es algo que no vas a utilizar diario y no necesitas invertir tanto tiempo, pues, algo simple como cut te va bien.

I have been playing with pdb for debugging code (introductory level)

Well, this is time to talk about something I have been playing, the pdb standard module python provides. I'll talk in the context of py 3.7+ since there are differences that improve how to work with this. Well, first of all, as you should found in this field and coding experiences and challenges. You have to deal with bugs, unexpected errors, or even worst, unexpected behavior which sometimes is most difficult to trace. Here are some lights on how to use it, this is really useful if your life is coding :). Consider the following commands table. Command Description s Execute the current line and stop at the first possible occasion. n Continue the execution until the next line in the current function is reached or it returns. p Shows the values of variables in context code. ll List the whole source code for the current function or frame l In contrast to ll, this command shows a shorter snippet of code. l. If you pass the param . to this command, it will show you always 11 li

How to delete one or more documents from your MongoDB repository

MongoDB seems to be complex at first sign, but in fact is not, you could perform a complete CRUD easily if you expend some time on the documentation. For example, lets say you need to delete some documents (rows, if you are thinking on a traditional RDBMS). First you want to find all these documents to be removed. > db.your_collection.find({ "cvectry": "MX", "layer_id": 20 }, {}) { "_id" : ObjectId("5e8123e8892355c921e6b436"), "layer_id" : 20 } > After finding all these documents to be removed, then you want to perform the following delete method as follow: > db.your_collection.remove({ "cvectry": "MX", "layer_id": 20 }, { justOne: true }) WriteResult({ "nRemoved" : 1 }) > In this case, after finding all these documents that match with "cvectry": "MX", "layer_id": 20. I got the result on the first command I ran, so I just wanted to delete just on