Movatterモバイル変換


[0]ホーム

URL:


PPTX, PDF1,452 views

BINARY files CSV files JSON files with example.pptx

BINARY FILES, CSV FILES

Embed presentation

Downloaded 10 times
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 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.
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 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
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)
import pickle//WRITE OPERATIONdef 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':breakpickle.dump(record,f)print("Records are added Successfully")f.close()
READ() Operationdef 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()://APPENDf=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':breakf.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=0try:while True:s=pickle.load(f)for i in s:if i[0]==r:print(i)found=1breakexcept 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)breakexcept 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:continuereclst.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
CSVCSV is an acronym 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:
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 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.
The csv.writer class has 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"])
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 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)
Csv.DictWriter()import csvmydict =[{'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 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])
Append()import csv# List that 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)
What is a Python 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.
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
#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])
Deleting a TupleSince tuples 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)
# create a tuple 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
• Python tuples follow 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.
# 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 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
Creating a Python Tuple 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 ,
# create a tuple 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’,)
Accessing Items From the 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
Built in methodsCount() Method• The count() method of Tuple returns the number of times the given elementappears in the tuple.tuple.count(element)
JSONThe 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 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 OBJECT PYTHON OBJECTobject dictarray liststring strnull Nonenumber (int) intnumber (real) floattrue Truefalse False
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.
# Python program to 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()
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 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.
json.dump() in Pythonimport json# 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()
import jsonperson = '{"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 jsonwith 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 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)
Using XML with Python• 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:
• 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 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
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
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 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.
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"}}}"""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 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)
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 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.
import jsonimport xmltodictfile=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.

Recommended

PPTX
Regular expressions,function and glob module.pptx
PPTX
Natural Language processing using nltk.pptx
PPTX
What is FIle and explanation of text files.pptx
PPTX
Handling Missing Data for Data Analysis.pptx
PPTX
python plotting's and its types with examples.pptx
PPTX
JSON, XML and Data Science introduction.pptx
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
PPTX
Mongodatabase with Python for Students.pptx
PPTX
Probability Distribution Reviewing Probability Distributions.pptx
PPTX
Python With MongoDB in advanced Python.pptx
PPTX
Statistics and its measures with Python.pptx
PPTX
PPTX
DataStructures in Pyhton Pandas and numpy.pptx
PPTX
Data file handling in python reading & writing methods
PDF
Python File Handling | File Operations in Python | Learn python programming |...
DOCX
Python Notes for mca i year students osmania university.docx
PPTX
Series data structure in Python Pandas.pptx
PDF
pandas: a Foundational Python Library for Data Analysis and Statistics
PDF
Python Modules
PDF
9 python data structure-2
PPTX
STRINGS IN PYTHON
PPTX
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
PDF
CSV Files-1.pdf
PDF
Python : Regular expressions
PPTX
Dictionary in python
PDF
Python programming : Strings
PPTX
File Handling Python
PPTX
01 file handling for class use class pptx
PPTX
File handling in Python

More Related Content

PPTX
Regular expressions,function and glob module.pptx
PPTX
Natural Language processing using nltk.pptx
PPTX
What is FIle and explanation of text files.pptx
PPTX
Handling Missing Data for Data Analysis.pptx
PPTX
python plotting's and its types with examples.pptx
PPTX
JSON, XML and Data Science introduction.pptx
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
PPTX
Mongodatabase with Python for Students.pptx
Regular expressions,function and glob module.pptx
Natural Language processing using nltk.pptx
What is FIle and explanation of text files.pptx
Handling Missing Data for Data Analysis.pptx
python plotting's and its types with examples.pptx
JSON, XML and Data Science introduction.pptx
Pyhton with Mysql to perform CRUD operations.pptx
Mongodatabase with Python for Students.pptx

What's hot

PPTX
Probability Distribution Reviewing Probability Distributions.pptx
PPTX
Python With MongoDB in advanced Python.pptx
PPTX
Statistics and its measures with Python.pptx
PPTX
PPTX
DataStructures in Pyhton Pandas and numpy.pptx
PPTX
Data file handling in python reading & writing methods
PDF
Python File Handling | File Operations in Python | Learn python programming |...
DOCX
Python Notes for mca i year students osmania university.docx
PPTX
Series data structure in Python Pandas.pptx
PDF
pandas: a Foundational Python Library for Data Analysis and Statistics
PDF
Python Modules
PDF
9 python data structure-2
PPTX
STRINGS IN PYTHON
PPTX
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
PDF
CSV Files-1.pdf
PDF
Python : Regular expressions
PPTX
Dictionary in python
PDF
Python programming : Strings
PPTX
File Handling Python
Probability Distribution Reviewing Probability Distributions.pptx
Python With MongoDB in advanced Python.pptx
Statistics and its measures with Python.pptx
DataStructures in Pyhton Pandas and numpy.pptx
Data file handling in python reading & writing methods
Python File Handling | File Operations in Python | Learn python programming |...
Python Notes for mca i year students osmania university.docx
Series data structure in Python Pandas.pptx
pandas: a Foundational Python Library for Data Analysis and Statistics
Python Modules
9 python data structure-2
STRINGS IN PYTHON
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
CSV Files-1.pdf
Python : Regular expressions
Dictionary in python
Python programming : Strings
File Handling Python

Similar to BINARY files CSV files JSON files with example.pptx

PPTX
01 file handling for class use class pptx
PPTX
File handling in Python
PPTX
FILE HANDLING.pptx
PPTX
File handling in pythan.pptx
PPTX
UNIT -III_Python file handling, reading and writing files.pptx
PDF
class 12 Unit 5 file handling.pdf skhnjhn
PDF
File handling with python class 12th .pdf
PDF
5.1 Binary File Handling.pdf
PPT
Python
PPTX
FILE HANDLING IN PYTHON Presentation Computer Science
PPTX
file handling in python using exception statement
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PPTX
file handling.pptx avlothaan pa thambi popa
PPTX
Python-The programming Language
PPTX
files.pptx
PPTX
Programming in Python
PPTX
Files and file objects (in Python)
PDF
ppt_pspp.pdf
PPTX
FIle Handling and dictionaries.pptx
PPTX
H file handling
01 file handling for class use class pptx
File handling in Python
FILE HANDLING.pptx
File handling in pythan.pptx
UNIT -III_Python file handling, reading and writing files.pptx
class 12 Unit 5 file handling.pdf skhnjhn
File handling with python class 12th .pdf
5.1 Binary File Handling.pdf
Python
FILE HANDLING IN PYTHON Presentation Computer Science
file handling in python using exception statement
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
file handling.pptx avlothaan pa thambi popa
Python-The programming Language
files.pptx
Programming in Python
Files and file objects (in Python)
ppt_pspp.pdf
FIle Handling and dictionaries.pptx
H file handling

More from Ramakrishna Reddy Bijjam

PPTX
Combining data and Customizing the Header NamesSorting.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
Data Frame Data structure in Python pandas.pptx
PPTX
Arrays to arrays and pointers with arrays.pptx
PPTX
Pointers and single &multi dimentionalarrays.pptx
Combining data and Customizing the Header NamesSorting.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
Data Frame Data structure in Python pandas.pptx
Arrays to arrays and pointers with arrays.pptx
Pointers and single &multi dimentionalarrays.pptx

Recently uploaded

PPTX
Anatomy of the eyeball An overviews.pptx
PDF
Past Memories and a New World: Photographs of Stoke Newington from the 70s, 8...
PDF
Agentic AI and AI Agents 20251121.pdf - by Ms. Oceana Wong
PDF
Conferencia de Abertura_Virgilio Almeida.pdf
PPTX
A Presentation of PMES 2025-2028 with Salient features.pptx
PDF
Deep Research and Analysis - by Ms. Oceana Wong
PPTX
Declaration of Helsinki Basic principles in medical research ppt.pptx
PPTX
Masterclass on Cybercrime, Scams & Safety Hacks.pptx
PDF
“Step-by-Step Fabrication of Bipolar Junction Transistors (BJTs)”
PDF
UGC NET Paper 1 Syllabus | 10 Units Complete Guide for NTA JRF
PPTX
Time Series Analysis - Meaning, Definition, Components and Application
PPTX
Screening and Selecting Studies for Systematic Review Dr Reginald Quansah
PDF
DEFINITION OF COMMUNITY Sociology. .pdf
PPTX
The hidden treasures Grade 5 Story with Motive Questions.pptx
PPTX
ATTENTION - PART 1.pptx cognitive processes -For B.Sc I Sem By Mrs.Shilpa Hot...
PPTX
What are New Features in Purchase _Odoo 18
PDF
LH_Lecture Note on Spices , AI And Importance in Human Life.pdf
PPTX
SEMESTER 5 UNIT- 1 Difference of Children and adults.pptx
PDF
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
PPTX
Prelims - History and Geography Quiz - Around the World in 80 Questions - IITK
Anatomy of the eyeball An overviews.pptx
Past Memories and a New World: Photographs of Stoke Newington from the 70s, 8...
Agentic AI and AI Agents 20251121.pdf - by Ms. Oceana Wong
Conferencia de Abertura_Virgilio Almeida.pdf
A Presentation of PMES 2025-2028 with Salient features.pptx
Deep Research and Analysis - by Ms. Oceana Wong
Declaration of Helsinki Basic principles in medical research ppt.pptx
Masterclass on Cybercrime, Scams & Safety Hacks.pptx
“Step-by-Step Fabrication of Bipolar Junction Transistors (BJTs)”
UGC NET Paper 1 Syllabus | 10 Units Complete Guide for NTA JRF
Time Series Analysis - Meaning, Definition, Components and Application
Screening and Selecting Studies for Systematic Review Dr Reginald Quansah
DEFINITION OF COMMUNITY Sociology. .pdf
The hidden treasures Grade 5 Story with Motive Questions.pptx
ATTENTION - PART 1.pptx cognitive processes -For B.Sc I Sem By Mrs.Shilpa Hot...
What are New Features in Purchase _Odoo 18
LH_Lecture Note on Spices , AI And Importance in Human Life.pdf
SEMESTER 5 UNIT- 1 Difference of Children and adults.pptx
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
Prelims - History and Geography Quiz - Around the World in 80 Questions - IITK

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()
  • 7.
    def search():f=open("student.dat","rb")r=int(input("Enter Rollnumer to be search..."))found=0try:while True:s=pickle.load(f)for i in s:if i[0]==r:print(i)found=1breakexcept EOFError:f.close()if found==0:print("Sorry..... no records found")
  • 8.
    def update():f=open("student.dat","rb+")r=int(input("Enter rollnumber 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)breakexcept Exception:f.close()
  • 9.
    def delete():f=open("student.dat","rb")s=pickle.load(f)f.close()r=int(input("Enter rollnumber to be deleted..."))f=open("student.dat","wb")print(s)reclst=[]for i in s:if i[0]==r:continuereclst.append(i)pickle.dump(reclst,f)f.close()
  • 10.
    def MainMenu():print("---------------------------------")print("1.Write datainto 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 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)
  • 16.
    Csv.DictWriter()import csvmydict =[{'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 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.
  • 31.
    JSON OBJECT PYTHONOBJECTobject dictarray liststring strnull Nonenumber (int) intnumber (real) floattrue Truefalse False
  • 32.
    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()
  • 37.
    import jsonperson ='{"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 jsonwith open('path_to_file/person.json','r') as f:data = json.load(f)# Output: {'name': 'Bob', 'languages': ['English', 'French']}print(data)
  • 39.
    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.
  • 47.
    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"}}}"""python_dict=json.loads(json_string)file=open("person.xml","w")xmltodict.unparse(python_dict,output=file)file.close()
  • 48.
    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.
  • 50.
    import jsonimport xmltodictfile=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.

[8]ページ先頭

©2009-2025 Movatter.jp