Almacenamiento de datos en CSV/JSON
Aprenda a guardar datos extraídos en formatos de archivo habituales, como CSV y JSON, para facilitar su portabilidad y análisis.
Almacenamiento de datos en CSV/JSON es una lección gratuita de Web Scraping & Bots en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Web Scraping & Bots, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Web Scraping & Bots incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Storing Your Scraped Data
After scraping, raw data is often in memory. To use it later, share it, or analyze it, you need to save it permanently.
This lesson introduces two popular file formats: CSV and JSON. They are simple, human-readable, and widely supported.
Meet CSV: Comma-Separated Values
CSV stands for Comma-Separated Values. It's a plain text file format used to store tabular data, like a spreadsheet.
Each line in a CSV file is a data record. Each record consists of one or more fields, separated by commas.
CSV: Simple Table Format
Imagine a simple table. Each row becomes a line, and each column value is separated by a comma. The first line often contains the column headers.
name,age,city
Alice,30,New York
Bob,24,LondonWriting to CSV with Python
Python's built-in csv module makes writing data to CSV files easy. We'll use csv.writer and writerow().
The 'w' mode opens the file for writing. newline='' prevents extra blank rows.
import csv
# Data to save
data = [
["name", "age", "city"],
["Alice", 30, "New York"],
["Bob", 24, "London"]
]
# Open the file in write mode
with open("people.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data) # Write all rows at once
print("Data saved to people.csv")JSON: JavaScript Object Notation
JSON (JavaScript Object Notation) is another popular, human-readable format. It's often used for sending data between web servers and web applications.
JSON organizes data into key-value pairs, similar to Python dictionaries, and lists.
JSON: Key-Value Pairs
JSON data is structured using objects ({}) and arrays ([]).
- An object holds key-value pairs (e.g.,
"name": "Alice"). - An array holds an ordered list of values (e.g.,
[{}, {}]).
[
{
"name": "Alice",
"age": 30,
"city": "New York"
},
{
"name": "Bob",
"age": 24,
"city": "London"
}
]Writing to JSON with Python
Python's built-in json module handles JSON data. We'll use json.dump() to write a Python dictionary or list to a file.
indent=2 makes the output file more readable by adding indentation.
import json
# Data to save (list of dictionaries)
data = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 24, "city": "London"}
]
# Open the file in write mode
with open("people.json", "w") as file:
json.dump(data, file, indent=2)
print("Data saved to people.json")Choosing the Right Format
Both CSV and JSON are great for data storage, but they excel in different scenarios:
- CSV: Best for simple tabular data, like spreadsheets. Easy to import into databases or Excel.
- JSON: Ideal for complex, hierarchical data. Great for APIs and when data structure might vary.
Reading Data Back
Just as you can write data, you can also read it back! Both csv and json modules provide functions for this.
csv.reader()for CSV files.json.load()for JSON files.
This allows you to load your scraped data back into Python for further processing.
Data Format Quiz
Which file format is generally better suited for storing hierarchical data with nested structures, like a list of products where each product has multiple attributes and possibly sub-items?
Lesson Summary
You've learned how to persist your scraped data!
- CSV: Ideal for tabular data, easy with Python's
csvmodule. - JSON: Great for hierarchical data, handled by Python's
jsonmodule. - Choose the format that best fits your data's structure and how you plan to use it.
Saving data is crucial for analysis and future use.
Preguntas frecuentes
¿La lección «Almacenamiento de datos en CSV/JSON» es gratis?
Sí — el texto completo de «Almacenamiento de datos en CSV/JSON» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Web Scraping & Bots, actualiza a CoddyKit PRO. El curso de Web Scraping & Bots incluye 4 lecciones en total.
¿Qué aprenderé en «Almacenamiento de datos en CSV/JSON»?
Aprenda a guardar datos extraídos en formatos de archivo habituales, como CSV y JSON, para facilitar su portabilidad y análisis. Practicas Web Scraping & Bots con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Web Scraping & Bots?
No se requiere experiencia previa. Web Scraping & Bots en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «Almacenamiento de datos en CSV/JSON»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Web Scraping & Bots?
Sí. Cada lección de Web Scraping & Bots incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Almacenamiento de datos en CSV/JSON
- Integración con bases de datos (SQL)
- Soluciones de almacenamiento en la nube
- Almacenamiento de datos en bases de datos NoSQL