1. CSV
CSV is an acronym for comma-separated values. It's a file format that you can
use to store tabular data, such as in a spreadsheet. You can also use it to store
data from a tabular database.
You can refer to each row in a CSV file as a data record. Each data record consists
of one or more fields, separated by commas.
The csv module has two classes that you can use in writing data to CSV. These
classes are:
Csv.writer()
Csv.DictWriter()
Csv.writer() class to write data into a CSV file. The class returns a writer object,
which you can then use to convert data into delimited strings.
To ensure that the newline characters inside the quoted fields interpret
correctly, open a CSV file object with newline=''.
The syntax for the csv.writer class is as follows:
2. The csv.writer class has two methods that you can use to write data to CSV files.
The methods are as follows:
import csv
with open('profiles1.csv', 'w', newline='') as file:
writer = csv.writer(file)
field = ["name", "age", "country"]
writer.writerow(field)
writer.writerow(["Oladele Damilola", "40", "Nigeria"])
writer.writerow(["Alina Hricko", "23", "Ukraine"])
writer.writerow(["Isabel Walter", "50", "United Kingdom"])
3. The writerows() method has similar usage to the writerow() method.
The only difference is that while the writerow() method writes a single row to a CSV
file, you can use the writerows() method to write multiple rows to a CSV file.
import csv
with open('profiles2.csv', 'w', newline='') as file:
writer = csv.writer(file)
row_list = [
["name", "age", "country"],
["Oladele Damilola", "40", "Nigeria"],
["Alina Hricko", "23" "Ukraine"],
["Isabel Walter", "50" "United Kingdom"],
]
writer.writerow(row_list)
5. Read()
Python provides various functions to read csv file. Few of them are discussed below as.
To see examples, we must have a csv file.
1. Using csv.reader() function
In Python, the csv.reader() module is used to read the csv file. It takes each row of the
file and makes a list of all the columns.
import csv
def main():
# To Open the CSV file
with open(' python.csv ', newline = '') as csv_file:
csv_read = csv.reader( csv_file, delimiter = ',')
# To Read and display each row
for row in csv_read:
print(row)
main()
6. Append()
from csv import writer
# List that we want to add as a new row
List = [6, 'William', 5532, 1, 'UAE']
# Open our existing CSV file in append mode
# Create a file object for this file
with open('event.csv', 'a') as f_object:
# Pass this file object to csv.writer()
# and get a writer object
writer_object = writer(f_object)
# Pass the list as an argument into
# the writerow()
writer_object.writerow(List)
# Close the file object
f_object.close()
7. JSON
The full form of JSON is JavaScript Object Notation. It means that a script
(executable) file which is made of text in a programming language, is used to
store and transfer the data.
Python supports JSON through a built-in package called JSON. To use this
feature, we import the JSON package in Python script
Deserialize a JSON String to an Object in Python
The Deserialization of JSON means the conversion of JSON objects into their
respective Python objects. The load()/loads() method is used for it.
8. JSON OBJECT PYTHON OBJECT
object dict
array list
string str
null None
number (int) int
number (real) float
true True
false False
9. • json.load() method
• The json.load() accepts the file object, parses the JSON data,
populates a Python dictionary with the data, and returns it back to
you.
• Syntax:
• json.load(file object)
• Parameter: It takes the file object as a parameter.
• Return: It return a JSON Object.
10.
11. • # Python program to read
• # json file
• import json
• # Opening JSON file
• f = open('data.json')
• # returns JSON object as
• data = json.load(f)
• # Iterating through the json
• # list
• for i in data['emp_details']:
• print(i)
• # Closing file
• f.close()
12. • json.loads() Method
• If we have a JSON string, we can parse it by using the json.loads() method.
• json.loads() does not take the file path, but the file contents as a string,
• to read the content of a JSON file we can use fileobject.read() to convert the file
into a string and pass it with json.loads(). This method returns the content of the
file.
• Syntax:
• json.loads(S)
• Parameter: it takes a string, bytes, or byte array instance which contains the JSON
document as a parameter (S).
• Return Type: It returns the Python object.
15. • import json
• with open('path_to_file/person.json', 'r') as f:
• data = json.load(f)
• # Output: {'name': 'Bob', 'languages': ['English', 'French']}
• print(data)
16. • Python Convert to JSON string
• You can convert a dictionary to JSON string using json.dumps() method.
• import json
• person_dict = {'name': 'Bob',
• 'age': 12,
• 'children': None
• }
• person_json = json.dumps(person_dict)
• # Output: {"name": "Bob", "age": 12, "children": null}
• print(person_json)
17. Using XML with Python
• Extensible Mark-up Language is a simple and flexible text format that
is used to exchange different data on the web
• It is a universal format for data on the web
• Why we use XML?
• Reuse: Contents are separated from presentation and we can reuse
• Portability: It is an international platform independent, so developers
can store their files safely
• Interchange: Interoperate and share data seamlessly
• Self-Describing:
18. • XML elements must have a closing tag
• Xml tags are case sensitive
• All XML elements must be properly nested
• All XML documents must have a root elements
• Attribute values must always be quoted
19. XML
• <?xml version="1.0"?>
• <employee>
• <name>John Doe</name>
• <age>35</age>
• <job>
• <title>Software Engineer</title>
• <department>IT</department>
• <years_of_experience>10</years_of_experience>
• </job>
• <address>
• <street>123 Main St.</street>
• <city>San Francisco</city>
• <state>CA</state>
• <zip>94102</zip>
• </address>
• </employee>
• In this XML, we have used the same data shown in the JSON file.
• You can observe that the elements in the XML files are stored using tags.
20. Here is an example of a simple JSON object:
• {
• "employee": {
• "name": "John Doe",
• "age": 35,
• "job": {
• "title": "Software Engineer",
• "department": "IT",
• "years_of_experience": 10
• },
• "address": {
• "street": "123 Main St.",
• "city": "San Francisco",
• "state": "CA",
• "zip": 94102
• }
• }
• }
• This JSON file contains details of an employee. You can observe that the data is stored as key-value pairs.
21. • To convert a JSON string to an XML string, we will first convert the
json string to a python dictionary.
• For this, we will use the loads() method defined in the json module.
• The loads() module takes the json string as its input argument and
returns the dictionary.
• Next, we will convert the python dictionary to XML using the
unparse() method defined in the xmltodict module.
• The unparse() method takes the python dictionary as its input
argument and returns an XML string.
Convert JSON String to XML String in Python
22. • import json
• import xmltodict
• json_string="""{"employee": {"name": "John Doe", "age": "35", "job":
{"title": "Software Engineer", "department": "IT", "years_of_experience":
"10"},"address": {"street": "123 Main St.", "city": "San Francisco", "state":
"CA", "zip": "94102"}}}
• """
• print("The JSON string is:")
• print(json_string)
• python_dict=json.loads(json_string)
• xml_string=xmltodict.unparse(python_dict)
• print("The XML string is:")
• print(xml_string)
• OUT PUT Will be in XML And JSON
23. JSON String to XML File in Python
• Instead of creating a string, we can also convert a JSON string to an XML file in python. For this, we will use
the following steps.
• first, we will convert the JSON string to a python dictionary using the loads() method defined in the json
module.
• Next, we will open an empty XML file using the open() function.
• The open() function takes the file name as its first input argument and the literal “w” as its second input
argument.
• After execution, it returns a file pointer.
• Once we get the file pointer, we will save the python dictionary to an XML file using the unparse() method
defined in the xmltodict module.
• The unparse() method takes the dictionary as its first argument and the file pointer as the argument to the
output parameter.
• After execution, it writes the XML file to the storage.
• Finally, we will close the XML file using the close() method.
25. Convert JSON File to XML String in Python
• To convert a JSON file to an XML string, we will first open the JSON file in
read mode using the open() function.
• The open() function takes the file name as its first input argument and the
python literal “r” as its second input argument. After execution, the open()
function returns a file pointer.
• import json
• import xmltodict
• file=open("person.json","r")
• python_dict=json.load(file)
• xml_string=xmltodict.unparse(python_dict)
• print("The XML string is:")
• print(xml_string)
26. JSON File to XML File in Python
• First, we will open the JSON file in read mode using the open() function.
• For this, we will pass the filename as the first input argument and the
literal “r” as the second input argument to the open() function.
• The open() function returns a file pointer.
• Next, we will load the json file into a python dictionary using the load()
method defined in the json module.
• The load() method takes the file pointer as its input argument and returns
a python dictionary.
• Now, we will open an XML file using the open() function.
• Then, we will save the python dictionary to the XML file using the unparse()
method defined in the xmltodict module.
• Finally, we will close the XML file using the close() method.
27. • import json
• import xmltodict
• file=open("person.json","r")
• python_dict=json.load(file)
• xml_file=open("person.xml","w")
• xmltodict.unparse(python_dict,output=xml_file)
• xml_file.close()
• After executing the above code, the content of the JSON file
"person.json" will be saved as XML in the "person.xml" file.