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()
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()
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)
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()
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.
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.