BINARY files CSV files JSON files with example.pptx
1.
BINARY FILES• Readingbinary 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 storedata 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 canuse 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 BinaryFile• To read a binary file, you need to use Python’s built-in open() function, but with the mode 'rb', which stands for readbinary.• The 'rb' mode tells Python that you intend to read the file in binaryformat, and it will not try to decode the data into a stringfile = open("file_name", "rb")Using read()• The open() function is used to open files in Python. When dealingwith 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 anewline byte (b'n’).with open('example.bin', 'rb') as f:lines = f.readlines()for i in lines:print(i)
4.
import pickle//WRITE OPERATIONdefwrite():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':breakpickle.dump(record,f)print("Records are added Successfully")f.close()
5.
READ() Operationdef read():print("Recordsin 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()://APPENDf=open("student.dat","rb+")print("Append recordsin 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':breakf.seek(0)pickle.dump(rec,f)print("Records are added Successfully")f.close()
while True:MainMenu()ch=int(input("Enter yourchoice.."))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.
CSVCSV is anacronym for comma-separated values. It's a file format that you can use tostore tabular data, such as in a spreadsheet. You can also use it to store data from atabular database.You can refer to each row in a CSV file as a data record. Each data record consists ofone or more fields, separated by commas.The csv module has two classes that you can use in writing data to CSV. These classesare:csv.writer()csv.DictWriter()Csv.writer() class to write data into a CSV file. The class returns a writer object, whichyou 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 ofa 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 openingthe 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-basedregions 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 adelimiter.Pipe (|):Sometimes used in more complex datasets to avoid conflicts with other delimiters.
14.
The csv.writer classhas two methods that you can use to write data to CSV files.The methods are as follows:import csvwith 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() methodhas similar usage to the writerow() method.The only difference is that while the writerow() method writes a single row to a CSVfile, you can use the writerows() method to write multiple rows to a CSV file.import csvwith 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)
Read()Python provides variousfunctions to read csv file. Few of them are discussedbelow as. To see examples, we must have a csv file.1. Using csv.reader() functionIn Python, the csv.reader() module is used to read the csv file. It takes each rowof the file and makes a list of all the columns.import csvwith 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# Listthat we want to add as a new rowdict1 = [{'name': 'RKREDDY', 'age': '34', 'country': 'India'}]fields = ['name', 'age', 'country']# Open our existing CSV file in append mode# Create a file object for this filewith 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 aPython Tuple?• A Python tuple is a collection of items or values. Some key differences between aPython 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’tbe changed.Creating a Python Tuple• Python tuple can be created by specifying comma separated values inside ofparentheses ( ).• 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 ofthem to be a number that is not odd. As you can see below, changing valuesinside of a tuple throws an error as tuples are immutable.
20.
Tuple CharacteristicsOrdered -They maintain the order of elements.Immutable - They cannot be changed after creation.Allow duplicates - They can contain duplicate values.Python Tuple Basic OperationsAccessing of Python TuplesConcatenation of TuplesSlicing of TupleDeleting a Tuple
21.
#Concatenation of Tuplestup1= (0, 1, 2, 3)tup2 = (‘avanthi', 'For', ‘avnt')tup3 = tup1 + tup2print(tup3)Slicing of TupleSlicing 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 elementprint(tup[1:])# Reversing the Tupleprint(tup[::-1])# Printing elements of a Rangeprint(tup[4:9])
22.
Deleting a TupleSincetuples are immutable, we cannot delete individual elements of atuple.However, we can delete an entire tuple using del statement.tup = (0, 1, 2, 3, 4)del tupprint(tup)
23.
# create atuple of first five odd numbersodd_numbers = (1, 3, 5, 7, 9)print(odd_numbers)(1, 3, 5, 7, 9)odd_numbers[1] = 2TypeError Traceback (most recent call last)<ipython-input-2-c99900bfc26b> in <module>-> 1 odd_numbers[1] = 2TypeError: ‘tuple' object does not support item assignment
24.
• Python tuplesfollow the idea of packing and unpacking values• i.e. while creating a tuple parentheses ( ) are optional and just providing acomma-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 beassigned to individual variables (also called unpacking).• Let’s create a tuple called student with name, age, course, phone numberusing PACKING and then UNPACK those values from the student tuple intoindividual variables.
25.
# create atuple called student while PACKING name, age, course and# phone number# note: as you can see parantheses are optional while packing values into tuplestudent = 'John Doe', 27, 'Python v3', 1234567890print (student)('John Doe', 27, 'Python v3', 1234567890)# let's unpack the values from student tuple into individual variablesname, age, course, phone = studentprint (name)print (age)print (course)print (phone)John Doe27Python v31234567890
26.
Creating a PythonTuple With Zero or One ItemCreating a python tuple with either zero or one element is a bit tricky. Let’stake 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 itemwith a comma ,
27.
# create atuple with zero elementsempty_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 Fromthe TupleItems from the tuple can be accessed just like a list usingIndexing – returns the itemNegative Indexing – returns the itemSlicing – returns a tuple with the items in itLet’s access course from student tuple using above mentioned techniquesstudent = 'John Doe', 27, 'Python v3', 1234567890print(student)('John Doe', 27, 'Python v3', 1234567890)# let's unpack the values from student tuple into individual variablesname, age, course, phone = student# get course from student tuple using indexingprint(student[-2])Python v3
29.
Built in methodsCount()Method• The count() method of Tuple returns the number of times the given elementappears in the tuple.tuple.count(element)
30.
JSONThe full formof JSON is JavaScript Object Notation. It means that a script(executable) file which is made of text in a programming language, is used tostore and transfer the data.Python supports JSON through a built-in package called JSON. To use thisfeature, we import the JSON package in Python scriptDeserialize a JSON String to an Object in PythonThe Deserialization of JSON means the conversion of JSON objects into theirrespective Python objects. The load()/loads() method is used for it.
json.load() methodThe json.load()accepts the file object, parses the JSON data, populatesa 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 programto read# json fileimport json# Opening JSON filef = open('data.json')# returns JSON object asdata = json.load(f)# Iterating through the json# listfor i in data['emp_details']:print(i)# Closing filef.close()
35.
json.loads() Method• Ifwe 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 astring 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 JSONdocument as a parameter (S).• Return Type: It returns the Python object.
36.
json.dump() in Pythonimportjson# python object(dictionary) to be dumpeddict1 ={"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 storedout_file = open("myfile.json", "w")json.dump(dict1, out_file, indent = 6)out_file.close()
Python Convert toJSON stringYou can convert a dictionary to JSON string using json.dumps() method.import jsonperson_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 withPython• Extensible Mark-up Language is a simple and flexible text format thatis 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 developerscan store their files safely• Interchange: Interoperate and share data seamlessly• Self-Describing:
41.
• XML elementsmust 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>SoftwareEngineer</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 anexample 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 converta JSON string to an XML string, we will first convert the jsonstring 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 returnsthe 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 argumentand returns an XML string.Convert JSON String to XML String in Python
45.
import jsonimport xmltodictjson_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 toXML 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 thefollowing 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 inputargument.• 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() methoddefined in the xmltodict module.• The unparse() method takes the dictionary as its first argument and the file pointer as the argument to theoutput parameter.• After execution, it writes the XML file to the storage.• Finally, we will close the XML file using the close() method.
Convert JSON Fileto XML String in Python• To convert a JSON file to an XML string, we will first open the JSON file inread mode using the open() function.• The open() function takes the file name as its first input argument and thepython literal “r” as its second input argument. After execution, the open()function returns a file pointer.import jsonimport xmltodictfile=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 toXML 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 apython 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.