SlideShare a Scribd company logo
BINARY FILES
• Reading binary files means reading data that is stored in a binary format,
which is not human-readable.
• Unlike text files, which store data as readable characters, binary files store
data as raw bytes.
• Binary files store data as a sequence of bytes.
Different Modes for Binary Files in Python
• When working with binary files in Python, there are specific modes we can
use to open them:
• 'rb': Read binary - Opens the file for reading in binary mode.
• 'wb': Write binary - Opens the file for writing in binary mode.
• 'ab': Append binary - Opens the file for appending in binary mode.
Opening a Binary File
• To read a binary file, you need to use Python’s built-
in open() function, but with the mode 'rb', which stands for read
binary.
• The 'rb' mode tells Python that you intend to read the file in binary
format, and it will not try to decode the data into a string
file = open("file_name", "rb")
Using read()
• The open() function is used to open files in Python. When dealing
with binary files, we need to specify the mode as 'rb' (read binary)
and then use read() to read the binary file
f = open('example.bin', 'rb')
bin = f.read()
print(bin)
f.close()
Using readlines()
• By using readlines() method we can read all lines in a file.
• However, in binary mode, it returns a list of lines, each ending with a
newline byte (b'n’).
with open('example.bin', 'rb') as f:
lines = f.readlines()
for i in lines:
print(i)
import pickle//WRITE OPERATION
def write():
f=open("Student.dat","wb")
record=[]
while True:
rno=int(input("Enter Roll Number....:"))
name=input("Enter Name...:")
marks=int(input("Enter Marks...:"))
data=[rno,name,marks]
record.append(data)
ch=input("Enter more records(Y/N)?")
if ch in 'Nn':
break
pickle.dump(record,f)
print("Records are added Successfully")
f.close()
READ() Operation
def read():
print("Records in the file is")
f=open("Student.dat","rb")
try:
while True:
s=pickle.load(f)
print(s)
for i in s:
print(i)
except Exception:
f.close()
def append()://APPEND
f=open("student.dat","rb+")
print("Append records in to a file...")
rec=pickle.load(f)
while True:
rno=int(input("Enter Roll Number....:"))
name=input("Enter Name...:")
marks=int(input("Enter Marks...:"))
data=[rno,name,marks]
rec.append(data)
ch=input("Enter more records(Y/N)?")
if ch in 'Nn':
break
f.seek(0)
pickle.dump(rec,f)
print("Records are added Successfully")
f.close()
def search():
f=open("student.dat","rb")
r=int(input("Enter Roll numer to be search..."))
found=0
try:
while True:
s=pickle.load(f)
for i in s:
if i[0]==r:
print(i)
found=1
break
except EOFError:
f.close()
if found==0:
print("Sorry..... no records found")
def update():
f=open("student.dat","rb+")
r=int(input("Enter roll number whose details to updated..."))
f.seek(0)
try:
while True:
rpos=f.tell()
s=pickle.load(f)
print(s)
for i in s:
if i[0]==r:
i[1]=input("Enter updated name")
i[2]=int(input("Enter Updated Marks"))
f.seek(rpos)
pickle.dump(s,f)
break
except Exception:
f.close()
def delete():
f=open("student.dat","rb")
s=pickle.load(f)
f.close()
r=int(input("Enter roll number to be deleted..."))
f=open("student.dat","wb")
print(s)
reclst=[]
for i in s:
if i[0]==r:
continue
reclst.append(i)
pickle.dump(reclst,f)
f.close()
def MainMenu():
print("---------------------------------")
print("1.Write data into a file..:")
print("2.Read data from a file..:")
print("3.Append record into a file..:")
print("4.Search data into a file..:")
print("5.Update the data into a file..:")
print("6.Delete record from a file..:")
print("7.Exit:")
while True:
MainMenu()
ch=int(input("Enter your choice.."))
if ch==1:
write()
elif ch==2:
read()
elif ch==3:
append()
elif ch==4:
search()
elif ch==5:
update()
elif ch==6:
delete()
elif ch==7:
break
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:
1. Purpose of a Delimiter:
A delimiter separates individual data fields or columns within each row of a CSV file.
It ensures that the data can be correctly parsed and interpreted when importing or opening
the file in software like spreadsheets or databases.
2. Common Delimiters:
Comma (,):
This is the most widely used and default delimiter for CSV files, especially in English-based
regions and software.
Semicolon (;):
Commonly used in European countries where a comma is used as the decimal separator.
Tab (t):
Used in Tab-Separated Values (TSV) files. While not universally supported, it can be used as a
delimiter.
Pipe (|):
Sometimes used in more complex datasets to avoid conflicts with other delimiters.
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([“Azam", "40", “India"])
writer.writerow([“akram", "23", “Pak"])
writer.writerow([“RK", “34", "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"],
[“Azam", "40", “India"],
[“Akram", "23" “Pak"],
[“RK", “34" "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
with open(‘profiles3.csv','r')as csv_file:
csv_reader=csv.reader(csv_file)
#print(csv_reader)
for i in scv_reader:
print(i)
#print(i[1])
Append()
import csv
# List that we want to add as a new row
dict1 = [{'name': 'RKREDDY', 'age': '34', 'country': 'India'}]
fields = ['name', 'age', 'country']
# Open our existing CSV file in append mode
# Create a file object for this file
with open('profiles3.csv', 'a') as file:
# Pass this file object to csv.writer()
writer = csv.DictWriter(file, fieldnames = fields)
writer.writeheader()
writer.writerows(dict1)
What is a Python Tuple?
• A Python tuple is a collection of items or values. Some key differences between a
Python tuple and Python List are:
• Python tuple are created by adding comma separated values inside parentheses
( )
• Python tuple are immutable wherein once values are added to tuple, they can’t
be changed.
Creating a Python Tuple
• Python tuple can be created by specifying comma separated values inside of
parentheses ( ).
• Values inside of a tuple cannot be modified once created.
• Let’s create a tuple of the first 5 odd numbers and then try to change one of
them to be a number that is not odd. As you can see below, changing values
inside of a tuple throws an error as tuples are immutable.
Tuple Characteristics
Ordered - They maintain the order of elements.
Immutable - They cannot be changed after creation.
Allow duplicates - They can contain duplicate values.
Python Tuple Basic Operations
Accessing of Python Tuples
Concatenation of Tuples
Slicing of Tuple
Deleting a Tuple
#Concatenation of Tuples
tup1 = (0, 1, 2, 3)
tup2 = (‘avanthi', 'For', ‘avnt')
tup3 = tup1 + tup2
print(tup3)
Slicing of Tuple
Slicing a tuple means creating a new tuple from a subset of elements of the original tuple.
The slicing syntax is tuple[start:stop:step].
tup = tuple(‘Avanthi college')
# Removing First element
print(tup[1:])
# Reversing the Tuple
print(tup[::-1])
# Printing elements of a Range
print(tup[4:9])
Deleting a Tuple
Since tuples are immutable, we cannot delete individual elements of a
tuple.
However, we can delete an entire tuple using del statement.
tup = (0, 1, 2, 3, 4)
del tup
print(tup)
# create a tuple of first five odd numbers
odd_numbers = (1, 3, 5, 7, 9)
print(odd_numbers)
(1, 3, 5, 7, 9)
odd_numbers[1] = 2
TypeError Traceback (most recent call last)
<ipython-input-2-c99900bfc26b> in <module>
-> 1 odd_numbers[1] = 2
TypeError: ‘tuple' object does not support item assignment
• Python tuples follow the idea of packing and unpacking values
• i.e. while creating a tuple parentheses ( ) are optional and just providing a
comma-separated value will create a tuple as well (also known as packing).
• Similarly, when trying to access each value in the tuple, the values can be
assigned to individual variables (also called unpacking).
• Let’s create a tuple called student with name, age, course, phone number
using PACKING and then UNPACK those values from the student tuple into
individual variables.
# create a tuple called student while PACKING name, age, course and
# phone number
# note: as you can see parantheses are optional while packing values into tuple
student = 'John Doe', 27, 'Python v3', 1234567890
print (student)
('John Doe', 27, 'Python v3', 1234567890)
# let's unpack the values from student tuple into individual variables
name, age, course, phone = student
print (name)
print (age)
print (course)
print (phone)
John Doe
27
Python v3
1234567890
Creating a Python Tuple With Zero or One Item
Creating a python tuple with either zero or one element is a bit tricky. Let’s
take a look.
Python tuple with zero item can be created by using empty parentheses ()
Python tuple with exactly one item can be created by ending the tuple item
with a comma ,
# create a tuple with zero elements
empty_tuple = ()
print(empty_tuple)
()
# create a tuple with exactly one element
# note: pay attention to how the value ends with a comma ,
singleton_v1 = ('first value',)
print(singleton _v1)
singleton_v2 = 'first value’,
print(singleton_v2)
('first value',)
(‘first value’,)
Accessing Items From the Tuple
Items from the tuple can be accessed just like a list using
Indexing – returns the item
Negative Indexing – returns the item
Slicing – returns a tuple with the items in it
Let’s access course from student tuple using above mentioned techniques
student = 'John Doe', 27, 'Python v3', 1234567890
print(student)
('John Doe', 27, 'Python v3', 1234567890)
# let's unpack the values from student tuple into individual variables
name, age, course, phone = student
# get course from student tuple using indexing
print(student[-2])
Python v3
Built in methods
Count() Method
• The count() method of Tuple returns the number of times the given element
appears in the tuple.
tuple.count(element)
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.
BINARY files CSV files JSON files with example.pptx
# 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

PPTX
What is FIle and explanation of text files.pptx
PPTX
Regular expressions,function and glob module.pptx
PPTX
Natural Language processing using nltk.pptx
PPTX
JSON, XML and Data Science introduction.pptx
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
DOCX
Python Notes for mca i year students osmania university.docx
PPTX
Files in Python.pptx
PDF
Set methods in python
What is FIle and explanation of text files.pptx
Regular expressions,function and glob module.pptx
Natural Language processing using nltk.pptx
JSON, XML and Data Science introduction.pptx
Pyhton with Mysql to perform CRUD operations.pptx
Python Notes for mca i year students osmania university.docx
Files in Python.pptx
Set methods in python

What's hot (20)

PPTX
FLOW OF CONTROL-INTRO PYTHON
PPT
File handling in C++
PPTX
Python in 30 minutes!
PDF
Python functions
PDF
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PPTX
Introduction to the basics of Python programming (part 1)
PPT
File in c
PDF
Introduction To Python
PPT
Functions in c++
PPTX
L21 io streams
PPT
Adv. python regular expression by Rj
PPTX
Uploading a file with php
PPTX
File Handling Python
PDF
C++11 concurrency
PPTX
PDF
Jetpack Compose a nova forma de implementar UI no Android
PPTX
C++ decision making
PPTX
FLOW OF CONTROL-INTRO PYTHON
File handling in C++
Python in 30 minutes!
Python functions
PYTHON PROGRAMMING NOTES RKREDDY.pdf
Introduction to the basics of Python programming (part 1)
File in c
Introduction To Python
Functions in c++
L21 io streams
Adv. python regular expression by Rj
Uploading a file with php
File Handling Python
C++11 concurrency
Jetpack Compose a nova forma de implementar UI no Android
C++ decision making
Ad

Similar to BINARY files CSV files JSON files with example.pptx (20)

PPTX
Python Workshop - Learn Python the Hard Way
PPT
Python File functions
PDF
Import Data using R
PPTX
Python-for-Data-Analysis.pptx
PPTX
UNIT III PYTHON.pptx python basic ppt ppt
PPTX
Aggregate.pptx
PPTX
CSV JSON and XML files in Python.pptx
PPTX
iPython
PPTX
H file handling
PPTX
Python_Unit_III.pptx
PDF
file handling.pdf
PPTX
Learn Python The Hard Way Presentation
PPTX
Data Visualization_pandas in hadoop.pptx
PPTX
01 file handling for class use class pptx
PDF
03 Geographic scripting in uDig - halfway between user and developer
PPTX
FILE HANDLING.pptx
PPTX
funadamentals of python programming language (right from scratch)
PDF
Python - Lecture 11
PPTX
AARAV NAYAN OPERATING SYSTEM LABORATORY PCA
Python Workshop - Learn Python the Hard Way
Python File functions
Import Data using R
Python-for-Data-Analysis.pptx
UNIT III PYTHON.pptx python basic ppt ppt
Aggregate.pptx
CSV JSON and XML files in Python.pptx
iPython
H file handling
Python_Unit_III.pptx
file handling.pdf
Learn Python The Hard Way Presentation
Data Visualization_pandas in hadoop.pptx
01 file handling for class use class pptx
03 Geographic scripting in uDig - halfway between user and developer
FILE HANDLING.pptx
funadamentals of python programming language (right from scratch)
Python - Lecture 11
AARAV NAYAN OPERATING SYSTEM LABORATORY PCA
Ad

More from Ramakrishna Reddy Bijjam (20)

PPTX
DataStructures in Pyhton Pandas and numpy.pptx
PPTX
Parsing HTML read and write operations and OS Module.pptx
DOCX
VBS control structures for if do whilw.docx
DOCX
Builtinfunctions in vbscript and its types.docx
DOCX
VBScript Functions procedures and arrays.docx
DOCX
VBScript datatypes and control structures.docx
PPTX
Numbers and global functions conversions .pptx
DOCX
Structured Graphics in dhtml and active controls.docx
DOCX
Filters and its types as wave shadow.docx
PPTX
JavaScript Arrays and its types .pptx
PPTX
JS Control Statements and Functions.pptx
PPTX
Code conversions binary to Gray vice versa.pptx
PDF
FIXED and FLOATING-POINT-REPRESENTATION.pdf
PPTX
Handling Missing Data for Data Analysis.pptx
PPTX
Data Frame Data structure in Python pandas.pptx
PPTX
Series data structure in Python Pandas.pptx
PPTX
Mongodatabase with Python for Students.pptx
PPTX
Arrays to arrays and pointers with arrays.pptx
PPTX
Python With MongoDB in advanced Python.pptx
PPTX
Pointers and single &multi dimentionalarrays.pptx
DataStructures in Pyhton Pandas and numpy.pptx
Parsing HTML read and write operations and OS Module.pptx
VBS control structures for if do whilw.docx
Builtinfunctions in vbscript and its types.docx
VBScript Functions procedures and arrays.docx
VBScript datatypes and control structures.docx
Numbers and global functions conversions .pptx
Structured Graphics in dhtml and active controls.docx
Filters and its types as wave shadow.docx
JavaScript Arrays and its types .pptx
JS Control Statements and Functions.pptx
Code conversions binary to Gray vice versa.pptx
FIXED and FLOATING-POINT-REPRESENTATION.pdf
Handling Missing Data for Data Analysis.pptx
Data Frame Data structure in Python pandas.pptx
Series data structure in Python Pandas.pptx
Mongodatabase with Python for Students.pptx
Arrays to arrays and pointers with arrays.pptx
Python With MongoDB in advanced Python.pptx
Pointers and single &multi dimentionalarrays.pptx

Recently uploaded (20)

PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Pre independence Education in Inndia.pdf
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
PPTX
Onica Farming 24rsclub profitable farm business
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Introduction and Scope of Bichemistry.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Open folder Downloads.pdf yes yes ges yes
PPTX
Pharma ospi slides which help in ospi learning
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
102 student loan defaulters named and shamed – Is someone you know on the list?
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Pre independence Education in Inndia.pdf
The Final Stretch: How to Release a Game and Not Die in the Process.
How to Manage Starshipit in Odoo 18 - Odoo Slides
UPPER GASTRO INTESTINAL DISORDER.docx
Onica Farming 24rsclub profitable farm business
O7-L3 Supply Chain Operations - ICLT Program
Insiders guide to clinical Medicine.pdf
Introduction and Scope of Bichemistry.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
O5-L3 Freight Transport Ops (International) V1.pdf
Open folder Downloads.pdf yes yes ges yes
Pharma ospi slides which help in ospi learning
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx

BINARY files CSV files JSON files with example.pptx

  • 1. BINARY FILES • Reading binary files means reading data that is stored in a binary format, which is not human-readable. • Unlike text files, which store data as readable characters, binary files store data as raw bytes. • Binary files store data as a sequence of bytes. Different Modes for Binary Files in Python • When working with binary files in Python, there are specific modes we can use to open them: • 'rb': Read binary - Opens the file for reading in binary mode. • 'wb': Write binary - Opens the file for writing in binary mode. • 'ab': Append binary - Opens the file for appending in binary mode.
  • 2. Opening a Binary File • To read a binary file, you need to use Python’s built- in open() function, but with the mode 'rb', which stands for read binary. • The 'rb' mode tells Python that you intend to read the file in binary format, and it will not try to decode the data into a string file = open("file_name", "rb") Using read() • The open() function is used to open files in Python. When dealing with binary files, we need to specify the mode as 'rb' (read binary) and then use read() to read the binary file
  • 3. f = open('example.bin', 'rb') bin = f.read() print(bin) f.close() Using readlines() • By using readlines() method we can read all lines in a file. • However, in binary mode, it returns a list of lines, each ending with a newline byte (b'n’). with open('example.bin', 'rb') as f: lines = f.readlines() for i in lines: print(i)
  • 4. import pickle//WRITE OPERATION def write(): f=open("Student.dat","wb") record=[] while True: rno=int(input("Enter Roll Number....:")) name=input("Enter Name...:") marks=int(input("Enter Marks...:")) data=[rno,name,marks] record.append(data) ch=input("Enter more records(Y/N)?") if ch in 'Nn': break pickle.dump(record,f) print("Records are added Successfully") f.close()
  • 5. READ() Operation def read(): print("Records in the file is") f=open("Student.dat","rb") try: while True: s=pickle.load(f) print(s) for i in s: print(i) except Exception: f.close()
  • 6. def append()://APPEND f=open("student.dat","rb+") print("Append records in to a file...") rec=pickle.load(f) while True: rno=int(input("Enter Roll Number....:")) name=input("Enter Name...:") marks=int(input("Enter Marks...:")) data=[rno,name,marks] rec.append(data) ch=input("Enter more records(Y/N)?") if ch in 'Nn': break f.seek(0) pickle.dump(rec,f) print("Records are added Successfully") f.close()
  • 7. def search(): f=open("student.dat","rb") r=int(input("Enter Roll numer to be search...")) found=0 try: while True: s=pickle.load(f) for i in s: if i[0]==r: print(i) found=1 break except EOFError: f.close() if found==0: print("Sorry..... no records found")
  • 8. def update(): f=open("student.dat","rb+") r=int(input("Enter roll number whose details to updated...")) f.seek(0) try: while True: rpos=f.tell() s=pickle.load(f) print(s) for i in s: if i[0]==r: i[1]=input("Enter updated name") i[2]=int(input("Enter Updated Marks")) f.seek(rpos) pickle.dump(s,f) break except Exception: f.close()
  • 9. def delete(): f=open("student.dat","rb") s=pickle.load(f) f.close() r=int(input("Enter roll number to be deleted...")) f=open("student.dat","wb") print(s) reclst=[] for i in s: if i[0]==r: continue reclst.append(i) pickle.dump(reclst,f) f.close()
  • 10. def MainMenu(): print("---------------------------------") print("1.Write data into a file..:") print("2.Read data from a file..:") print("3.Append record into a file..:") print("4.Search data into a file..:") print("5.Update the data into a file..:") print("6.Delete record from a file..:") print("7.Exit:")
  • 11. while True: MainMenu() ch=int(input("Enter your choice..")) if ch==1: write() elif ch==2: read() elif ch==3: append() elif ch==4: search() elif ch==5: update() elif ch==6: delete() elif ch==7: break
  • 12. 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:
  • 13. 1. Purpose of a Delimiter: A delimiter separates individual data fields or columns within each row of a CSV file. It ensures that the data can be correctly parsed and interpreted when importing or opening the file in software like spreadsheets or databases. 2. Common Delimiters: Comma (,): This is the most widely used and default delimiter for CSV files, especially in English-based regions and software. Semicolon (;): Commonly used in European countries where a comma is used as the decimal separator. Tab (t): Used in Tab-Separated Values (TSV) files. While not universally supported, it can be used as a delimiter. Pipe (|): Sometimes used in more complex datasets to avoid conflicts with other delimiters.
  • 14. 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([“Azam", "40", “India"]) writer.writerow([“akram", "23", “Pak"]) writer.writerow([“RK", “34", "United Kingdom"])
  • 15. 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"], [“Azam", "40", “India"], [“Akram", "23" “Pak"], [“RK", “34" "United Kingdom"], ] writer.writerow(row_list)
  • 16. 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()
  • 17. 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 with open(‘profiles3.csv','r')as csv_file: csv_reader=csv.reader(csv_file) #print(csv_reader) for i in scv_reader: print(i) #print(i[1])
  • 18. Append() import csv # List that we want to add as a new row dict1 = [{'name': 'RKREDDY', 'age': '34', 'country': 'India'}] fields = ['name', 'age', 'country'] # Open our existing CSV file in append mode # Create a file object for this file with open('profiles3.csv', 'a') as file: # Pass this file object to csv.writer() writer = csv.DictWriter(file, fieldnames = fields) writer.writeheader() writer.writerows(dict1)
  • 19. What is a Python Tuple? • A Python tuple is a collection of items or values. Some key differences between a Python tuple and Python List are: • Python tuple are created by adding comma separated values inside parentheses ( ) • Python tuple are immutable wherein once values are added to tuple, they can’t be changed. Creating a Python Tuple • Python tuple can be created by specifying comma separated values inside of parentheses ( ). • Values inside of a tuple cannot be modified once created. • Let’s create a tuple of the first 5 odd numbers and then try to change one of them to be a number that is not odd. As you can see below, changing values inside of a tuple throws an error as tuples are immutable.
  • 20. Tuple Characteristics Ordered - They maintain the order of elements. Immutable - They cannot be changed after creation. Allow duplicates - They can contain duplicate values. Python Tuple Basic Operations Accessing of Python Tuples Concatenation of Tuples Slicing of Tuple Deleting a Tuple
  • 21. #Concatenation of Tuples tup1 = (0, 1, 2, 3) tup2 = (‘avanthi', 'For', ‘avnt') tup3 = tup1 + tup2 print(tup3) Slicing of Tuple Slicing a tuple means creating a new tuple from a subset of elements of the original tuple. The slicing syntax is tuple[start:stop:step]. tup = tuple(‘Avanthi college') # Removing First element print(tup[1:]) # Reversing the Tuple print(tup[::-1]) # Printing elements of a Range print(tup[4:9])
  • 22. Deleting a Tuple Since tuples are immutable, we cannot delete individual elements of a tuple. However, we can delete an entire tuple using del statement. tup = (0, 1, 2, 3, 4) del tup print(tup)
  • 23. # create a tuple of first five odd numbers odd_numbers = (1, 3, 5, 7, 9) print(odd_numbers) (1, 3, 5, 7, 9) odd_numbers[1] = 2 TypeError Traceback (most recent call last) <ipython-input-2-c99900bfc26b> in <module> -> 1 odd_numbers[1] = 2 TypeError: ‘tuple' object does not support item assignment
  • 24. • Python tuples follow the idea of packing and unpacking values • i.e. while creating a tuple parentheses ( ) are optional and just providing a comma-separated value will create a tuple as well (also known as packing). • Similarly, when trying to access each value in the tuple, the values can be assigned to individual variables (also called unpacking). • Let’s create a tuple called student with name, age, course, phone number using PACKING and then UNPACK those values from the student tuple into individual variables.
  • 25. # create a tuple called student while PACKING name, age, course and # phone number # note: as you can see parantheses are optional while packing values into tuple student = 'John Doe', 27, 'Python v3', 1234567890 print (student) ('John Doe', 27, 'Python v3', 1234567890) # let's unpack the values from student tuple into individual variables name, age, course, phone = student print (name) print (age) print (course) print (phone) John Doe 27 Python v3 1234567890
  • 26. Creating a Python Tuple With Zero or One Item Creating a python tuple with either zero or one element is a bit tricky. Let’s take a look. Python tuple with zero item can be created by using empty parentheses () Python tuple with exactly one item can be created by ending the tuple item with a comma ,
  • 27. # create a tuple with zero elements empty_tuple = () print(empty_tuple) () # create a tuple with exactly one element # note: pay attention to how the value ends with a comma , singleton_v1 = ('first value',) print(singleton _v1) singleton_v2 = 'first value’, print(singleton_v2) ('first value',) (‘first value’,)
  • 28. Accessing Items From the Tuple Items from the tuple can be accessed just like a list using Indexing – returns the item Negative Indexing – returns the item Slicing – returns a tuple with the items in it Let’s access course from student tuple using above mentioned techniques student = 'John Doe', 27, 'Python v3', 1234567890 print(student) ('John Doe', 27, 'Python v3', 1234567890) # let's unpack the values from student tuple into individual variables name, age, course, phone = student # get course from student tuple using indexing print(student[-2]) Python v3
  • 29. Built in methods Count() Method • The count() method of Tuple returns the number of times the given element appears in the tuple. tuple.count(element)
  • 30. 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.
  • 31. JSON OBJECT PYTHON OBJECT object dict array list string str null None number (int) int number (real) float true True false False
  • 32. 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.
  • 34. # 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()
  • 35. 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.
  • 36. 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()
  • 37. 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'])
  • 38. import json with open('path_to_file/person.json', 'r') as f: data = json.load(f) # Output: {'name': 'Bob', 'languages': ['English', 'French']} print(data)
  • 39. 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)
  • 40. 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:
  • 41. • 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
  • 42. 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.
  • 43. 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.
  • 44. • 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
  • 45. 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
  • 46. 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.
  • 47. 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()
  • 48. 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)
  • 49. 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.
  • 50. 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.