SlideShare a Scribd company logo
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

Heap management in Compiler Construction
Heap management in Compiler ConstructionHeap management in Compiler Construction
Heap management in Compiler Construction
Muhammad Haroon
 
Android Memory Management
Android Memory ManagementAndroid Memory Management
Android Memory Management
Sadmankabirsoumik
 
Caching
CachingCaching
Caching
Nascenia IT
 
Run time storage
Run time storageRun time storage
Run time storage
Rasineni Madhan Mohan Naidu
 
Instruction Level Parallelism Compiler optimization Techniques Anna Universit...
Instruction Level Parallelism Compiler optimization Techniques Anna Universit...Instruction Level Parallelism Compiler optimization Techniques Anna Universit...
Instruction Level Parallelism Compiler optimization Techniques Anna Universit...
Dr.K. Thirunadana Sikamani
 
Algorithm Complexity & Big-O Analysis
Algorithm Complexity & Big-O AnalysisAlgorithm Complexity & Big-O Analysis
Algorithm Complexity & Big-O Analysis
Ömer Faruk Öztürk
 
Helpful logging with python
Helpful logging with pythonHelpful logging with python
Helpful logging with python
roskakori
 
Chapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata TheoryChapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata Theory
Tsegazeab Asgedom
 
Clean architecture
Clean architectureClean architecture
Clean architecture
Chris Houng
 
Map reduce prashant
Map reduce prashantMap reduce prashant
Map reduce prashant
Prashant Gupta
 
Compiler Design Unit 4
Compiler Design Unit 4Compiler Design Unit 4
Compiler Design Unit 4
Jena Catherine Bel D
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv files
keeeerty
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
JavaScript
JavaScriptJavaScript
JavaScript
Vidyut Singhania
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Detecting headless browsers
Detecting headless browsersDetecting headless browsers
Detecting headless browsers
Sergey Shekyan
 

What's hot (20)

Pipeline
PipelinePipeline
Pipeline
 
Html frames
Html framesHtml frames
Html frames
 
Heap management in Compiler Construction
Heap management in Compiler ConstructionHeap management in Compiler Construction
Heap management in Compiler Construction
 
Android Memory Management
Android Memory ManagementAndroid Memory Management
Android Memory Management
 
Caching
CachingCaching
Caching
 
Run time storage
Run time storageRun time storage
Run time storage
 
Huffman Coding
Huffman CodingHuffman Coding
Huffman Coding
 
Instruction Level Parallelism Compiler optimization Techniques Anna Universit...
Instruction Level Parallelism Compiler optimization Techniques Anna Universit...Instruction Level Parallelism Compiler optimization Techniques Anna Universit...
Instruction Level Parallelism Compiler optimization Techniques Anna Universit...
 
Algorithm Complexity & Big-O Analysis
Algorithm Complexity & Big-O AnalysisAlgorithm Complexity & Big-O Analysis
Algorithm Complexity & Big-O Analysis
 
Helpful logging with python
Helpful logging with pythonHelpful logging with python
Helpful logging with python
 
Chapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata TheoryChapter1 Formal Language and Automata Theory
Chapter1 Formal Language and Automata Theory
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Map reduce prashant
Map reduce prashantMap reduce prashant
Map reduce prashant
 
Compiler Design Unit 4
Compiler Design Unit 4Compiler Design Unit 4
Compiler Design Unit 4
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv files
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Detecting headless browsers
Detecting headless browsersDetecting headless browsers
Detecting headless browsers
 

Similar to CSV JSON and XML files in Python.pptx

JSON_FIles-Py (2).pptx
JSON_FIles-Py (2).pptxJSON_FIles-Py (2).pptx
JSON_FIles-Py (2).pptx
sravanicharugundla1
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
Skillwise Group
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
deepak kumbhar
 
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
AmitSharma397241
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim 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-phpapp01
Rex Joe
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Working with JSON
Working with JSONWorking 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...
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)
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
Laurence Svekis ✔
 
R data interfaces
R data interfacesR data interfaces
R data interfaces
Bhavesh Sarvaiya
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
Rafael Montesinos Muñoz
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
Lifna C.S
 
File Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering pptFile Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering ppt
pinuadarsh04
 
C
CC
Python crush course
Python crush coursePython crush course
Python crush course
Mohammed El Rafie Tarabay
 

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)
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
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
 
File Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering pptFile Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering ppt
 
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
 

More from Ramakrishna Reddy Bijjam

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
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.pptx
Ramakrishna Reddy Bijjam
 
Auxiliary, Cache and Virtual memory.pptx
Auxiliary, Cache and Virtual memory.pptxAuxiliary, Cache and Virtual memory.pptx
Auxiliary, Cache and Virtual memory.pptx
Ramakrishna 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.pptx
Ramakrishna Reddy Bijjam
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna 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 .pptx
Ramakrishna Reddy Bijjam
 
Auxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptxAuxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptx
Ramakrishna Reddy Bijjam
 
Random Forest Decision Tree.pptx
Random Forest Decision Tree.pptxRandom Forest Decision Tree.pptx
Random Forest Decision Tree.pptx
Ramakrishna Reddy Bijjam
 
K Means Clustering in ML.pptx
K Means Clustering in ML.pptxK Means Clustering in ML.pptx
K Means Clustering in ML.pptx
Ramakrishna Reddy Bijjam
 
Pandas.pptx
Pandas.pptxPandas.pptx
Python With MongoDB.pptx
Python With MongoDB.pptxPython With MongoDB.pptx
Python With MongoDB.pptx
Ramakrishna Reddy Bijjam
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
Ramakrishna Reddy Bijjam
 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
Ramakrishna Reddy Bijjam
 
BInary file Operations.pptx
BInary file Operations.pptxBInary file Operations.pptx
BInary file Operations.pptx
Ramakrishna Reddy Bijjam
 
Data Science in Python.pptx
Data Science in Python.pptxData Science in Python.pptx
Data Science in Python.pptx
Ramakrishna Reddy Bijjam
 
HTML files in python.pptx
HTML files in python.pptxHTML files in python.pptx
HTML files in python.pptx
Ramakrishna Reddy Bijjam
 
Regular Expressions in Python.pptx
Regular Expressions in Python.pptxRegular Expressions in Python.pptx
Regular Expressions in Python.pptx
Ramakrishna Reddy Bijjam
 
datareprersentation 1.pptx
datareprersentation 1.pptxdatareprersentation 1.pptx
datareprersentation 1.pptx
Ramakrishna Reddy Bijjam
 
Apriori.pptx
Apriori.pptxApriori.pptx
Eclat.pptx
Eclat.pptxEclat.pptx

More from Ramakrishna Reddy Bijjam (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
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
 

Recently uploaded

Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 

Recently uploaded (20)

Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.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.