SlideShare a Scribd company logo
1 of 27
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:
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"])
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)
Csv.DictWriter()
import csv
mydict =[{'name': 'Kelvin Gates', 'age': '19', 'country': 'USA'},
{'name': 'Blessing Iroko', 'age': '25', 'country': 'Nigeria'},
{'name': 'Idong Essien', 'age': '42', 'country': 'Ghana'}]
fields = ['name', 'age', 'country']
with open('profiles3.csv', 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames = fields)
writer.writeheader()
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()
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()
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.
JSON OBJECT PYTHON OBJECT
object dict
array list
string str
null None
number (int) int
number (real) float
true True
false False
• 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.
• # 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()
• 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.
• json.dump() in Python
• import json
•
• # python object(dictionary) to be dumped
• dict1 ={
• "emp1": {
• "name": "Lisa",
• "designation": "programmer",
• "age": "34",
• "salary": "54000"
• },
• "emp2": {
• "name": "Elis",
• "designation": "Trainee",
• "age": "24",
• "salary": "40000"
• },
• }
•
• # the json file where the output must be stored
• out_file = open("myfile.json", "w")
•
• json.dump(dict1, out_file, indent = 6)
•
• out_file.close()
• import json
• person = '{"name": "Bob", "languages": ["English", "French"]}'
• person_dict = json.loads(person)
• # Output: {'name': 'Bob', 'languages': ['English', 'French']}
• print( person_dict)
• # Output: ['English', 'French']
• print(person_dict['languages'])
• import json
• with open('path_to_file/person.json', 'r') as f:
• data = json.load(f)
• # Output: {'name': 'Bob', 'languages': ['English', 'French']}
• print(data)
• 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)
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:
• 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
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.
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.
• 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
• 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
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.
• 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"}}}
• """
• python_dict=json.loads(json_string)
• file=open("person.xml","w")
• xmltodict.unparse(python_dict,output=file)
• file.close()
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)
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.
• 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.

More Related Content

What's hot

How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaEdureka!
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data AnalysisAndrew Henshaw
 
Relational database system for restaurant
Relational database system for restaurantRelational database system for restaurant
Relational database system for restaurantLogedi Lusala
 
JSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked DataJSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked DataGregg Kellogg
 
Develop Android app using Golang
Develop Android app using GolangDevelop Android app using Golang
Develop Android app using GolangSeongJae Park
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and SetsNicole Ryan
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDBMongoDB
 
Manual del Programador Juego Ahorcado Educativo
Manual del Programador Juego Ahorcado EducativoManual del Programador Juego Ahorcado Educativo
Manual del Programador Juego Ahorcado EducativoJerry Alexander RC
 
For Loops and Nesting in Python
For Loops and Nesting in PythonFor Loops and Nesting in Python
For Loops and Nesting in Pythonprimeteacher32
 
c# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventionsc# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming ConventionsMicheal Ogundero
 

What's hot (20)

How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | Edureka
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data Analysis
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Relational database system for restaurant
Relational database system for restaurantRelational database system for restaurant
Relational database system for restaurant
 
JSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked DataJSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked Data
 
Develop Android app using Golang
Develop Android app using GolangDevelop Android app using Golang
Develop Android app using Golang
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String MethodsPython Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
 
Naming Conventions
Naming ConventionsNaming Conventions
Naming Conventions
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
JSON-LD and MongoDB
JSON-LD and MongoDBJSON-LD and MongoDB
JSON-LD and MongoDB
 
Manual del Programador Juego Ahorcado Educativo
Manual del Programador Juego Ahorcado EducativoManual del Programador Juego Ahorcado Educativo
Manual del Programador Juego Ahorcado Educativo
 
Lists
ListsLists
Lists
 
For Loops and Nesting in Python
For Loops and Nesting in PythonFor Loops and Nesting in Python
For Loops and Nesting in Python
 
Functions in python
Functions in python Functions in python
Functions in python
 
c# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventionsc# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventions
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 

Similar to CSV JSON and XML files in Python.pptx

JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)Skillwise Group
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college projectAmitSharma397241
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...HemaSenthil5
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Rex Joe
 
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...amit kuraria
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)Faysal Shaarani (MBA)
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in pythonLifna C.S
 
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesWebscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesJonathan Katz
 

Similar to CSV JSON and XML files in Python.pptx (20)

JSON_FIles-Py (2).pptx
JSON_FIles-Py (2).pptxJSON_FIles-Py (2).pptx
JSON_FIles-Py (2).pptx
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
Working with JSON
Working with JSONWorking with JSON
Working with JSON
 
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
 
R data interfaces
R data interfacesR data interfaces
R data interfaces
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
C
CC
C
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Python crush course
Python crush coursePython crush course
Python crush course
 
JSON,XML.pptx
JSON,XML.pptxJSON,XML.pptx
JSON,XML.pptx
 
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesWebscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
 

More from Ramakrishna Reddy Bijjam

Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxRamakrishna Reddy Bijjam
 
Python With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptxPython With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptxRamakrishna Reddy Bijjam
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxRamakrishna Reddy Bijjam
 
Certinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptxCertinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptxRamakrishna Reddy Bijjam
 
Auxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptxAuxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptxRamakrishna Reddy Bijjam
 

More from Ramakrishna Reddy Bijjam (20)

Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
 
Auxiliary, Cache and Virtual memory.pptx
Auxiliary, Cache and Virtual memory.pptxAuxiliary, Cache and Virtual memory.pptx
Auxiliary, Cache and Virtual memory.pptx
 
Python With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptxPython With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptx
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
Certinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptxCertinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptx
 
Auxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptxAuxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptx
 
Random Forest Decision Tree.pptx
Random Forest Decision Tree.pptxRandom Forest Decision Tree.pptx
Random Forest Decision Tree.pptx
 
K Means Clustering in ML.pptx
K Means Clustering in ML.pptxK Means Clustering in ML.pptx
K Means Clustering in ML.pptx
 
Pandas.pptx
Pandas.pptxPandas.pptx
Pandas.pptx
 
Python With MongoDB.pptx
Python With MongoDB.pptxPython With MongoDB.pptx
Python With MongoDB.pptx
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
 
BInary file Operations.pptx
BInary file Operations.pptxBInary file Operations.pptx
BInary file Operations.pptx
 
Data Science in Python.pptx
Data Science in Python.pptxData Science in Python.pptx
Data Science in Python.pptx
 
HTML files in python.pptx
HTML files in python.pptxHTML files in python.pptx
HTML files in python.pptx
 
Regular Expressions in Python.pptx
Regular Expressions in Python.pptxRegular Expressions in Python.pptx
Regular Expressions in Python.pptx
 
datareprersentation 1.pptx
datareprersentation 1.pptxdatareprersentation 1.pptx
datareprersentation 1.pptx
 
Apriori.pptx
Apriori.pptxApriori.pptx
Apriori.pptx
 
Eclat.pptx
Eclat.pptxEclat.pptx
Eclat.pptx
 
Time Series.pptx
Time Series.pptxTime Series.pptx
Time Series.pptx
 

Recently uploaded

EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Recently uploaded (20)

EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 

CSV JSON and XML files in Python.pptx

  • 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)
  • 4. Csv.DictWriter() import csv mydict =[{'name': 'Kelvin Gates', 'age': '19', 'country': 'USA'}, {'name': 'Blessing Iroko', 'age': '25', 'country': 'Nigeria'}, {'name': 'Idong Essien', 'age': '42', 'country': 'Ghana'}] fields = ['name', 'age', 'country'] with open('profiles3.csv', 'w', newline='') as file: writer = csv.DictWriter(file, fieldnames = fields) writer.writeheader()
  • 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.
  • 13. • json.dump() in Python • import json • • # python object(dictionary) to be dumped • dict1 ={ • "emp1": { • "name": "Lisa", • "designation": "programmer", • "age": "34", • "salary": "54000" • }, • "emp2": { • "name": "Elis", • "designation": "Trainee", • "age": "24", • "salary": "40000" • }, • } • • # the json file where the output must be stored • out_file = open("myfile.json", "w") • • json.dump(dict1, out_file, indent = 6) • • out_file.close()
  • 14. • import json • person = '{"name": "Bob", "languages": ["English", "French"]}' • person_dict = json.loads(person) • # Output: {'name': 'Bob', 'languages': ['English', 'French']} • print( person_dict) • # Output: ['English', 'French'] • print(person_dict['languages'])
  • 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.
  • 24. • 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"}}} • """ • python_dict=json.loads(json_string) • file=open("person.xml","w") • xmltodict.unparse(python_dict,output=file) • file.close()
  • 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.