When working with data in Python, it is common to encounter files in different formats such as CSV, JSON, and XML. These file formats allow us to store and exchange structured data, and Python provides several libraries to handle them easily. In this article, we will explore the basics of CSV, JSON, and XML file handling in Python.
CSV (Comma-Separated Values) is a simple file format used to store tabular data. Each line in a CSV file represents a row, and the values in each row are separated by commas. Python provides the built-in csv
module to read from and write to CSV files.
To read data from a CSV file, you can use the csv.reader
object. Here's an example:
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
To write data to a CSV file, you can use the csv.writer
object. Here's an example:
import csv
data = [
['Name', 'Age', 'Country'],
['John', 25, 'USA'],
['Sarah', 30, 'Canada'],
['Michael', 35, 'Australia']
]
with open('new_data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is commonly used to transmit data between a web server and a web application. Python provides the json
module to handle JSON files.
To read data from a JSON file, you can use the json.load
function. Here's an example:
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
To write data to a JSON file, you can use the json.dump
function. Here's an example:
import json
data = {
'name': 'John',
'age': 25,
'country': 'USA'
}
with open('new_data.json', 'w') as file:
json.dump(data, file)
XML (eXtensible Markup Language) is a markup language that defines rules for encoding documents. It is widely used for representing structured data. Python provides the xml
module to handle XML files.
To read data from an XML file, you can use the xml.etree.ElementTree
module. Here's an example:
import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
for child in root:
print(child.tag, child.attrib)
To write data to an XML file, you can create an XML tree using the xml.etree.ElementTree
module and then write it to a file. Here's an example:
import xml.etree.ElementTree as ET
root = ET.Element('data')
child1 = ET.SubElement(root, 'item')
child1.text = 'value1'
child2 = ET.SubElement(root, 'item')
child2.text = 'value2'
tree = ET.ElementTree(root)
tree.write('new_data.xml')
CSV, JSON, and XML are popular file formats used for storing and exchanging structured data. Python provides convenient modules such as csv
, json
, and xml
to handle these file formats effortlessly. By using these modules, you can read data from these files, manipulate it, and write it back in a format suitable for your needs.
noob to master © copyleft