SlideShare a Scribd company logo
Files
Team Emertxe
Introduction
Introduction

A file is an object on a computer that stores data, information, settings, or commands used
with a computer program

Advantages of files

- Data is stored permanently

- Updation becomes easy

- Data can be shared among various programs

- Huge amount of data can be stored
Files
Types
Text Binary
Stores the data in the form of strings Stores data in the form of bytes
Example:
“Ram” is stored as 3 characters
890.45 is stored as 6 characters
Example:
“Ram” is stored as 3 bytes
89000.45 is stored as 8 bytes
Examples:
.txt, .c, .cpp
Examples:
.jpg, .gif or .png
Files
Opening a file
Name open()
Syntax file_handler = open("file_name", "open_mode", "buffering")
filename : Name of the file to be opened
open_mode: Purpose of opening the file
buffering: Used to stored the data temporarily
Opening Modes
w - To write the data
- If file already exist, the data will be lost
r - To read the data
- The file pointer is positioned at the begining of the file
a - To append data to the file
- The file pointer is placed at the end of the file
w+ - To write and read data
- The previous data will be deleted
r+ - To read and write
- The previous data will not be deleted
- The file pointer is placed at the begining of the file
a+ - To append and read data
- The file pointer will be at the end of the file
x - To open the file in exclusive creation mode
- The file creation fails, if already file exist
Example
f = open("myfile.txt", "w")
Here, buffer is optional, if omitted 4096 / 8192 bytes will be considered.
Files
Closing a file
Name close()
Syntax f.close()
Example #Open the file
f = open("myfile.txt", "w")
#Read the string
str = input("Enter the string: ")
#Write the string into the file
f.write(str)
#Close the file
f.close()
Files
Working with text files containing strings
To read the content from files,
f.read() : Reads all lines, displays line by line
f.readlines() : Displays all strings as elements in a list
f.read().splitlines(): To suppress the "n" in the list
Program
#To create a text file to store strings
#Open the file
f = open("myfile.txt", "r")
#Read the data from a file
str = f.read() #Reads all data
#Display the data
print(str)
#Close the file
f.close()
Note:
"""
f.read(n): Will read 'n' bytes from the file
"""
Files
Working with text files containing strings
f.seek(offset, fromwhere)
- offset : No. of bytes to move
- fromwhere : Begining, Current, End
- Example : f.seek(10, 0), move file handler from Beg forward 10 bytes.
# Appending and then reading strings, Open the file for reading data
f = open('myfile.txt', 'a+')
print('Enter text to append(@ at end): ')
while str != '@':
str = input() # accept string into str
# Write the string into file
if (str != '@'):
f.write(str+"n")
# Put the file pointer to the beginning of the file
f.seek(0,0)
# Read strings from the file
print('The file cotents are: ')
str = f.read()
print(str)
# Closing the file
f.close()
Files
Knowing If file exists or not
Sample:
if os.path.isfile(fname):
f = open(fname, "r")
else:
print(fname + "Does not exist")
sys.exit() #Terminate the program
# Checking if file exists and then reading data
import os, sys
# open the file for reading data
fname = input('Enter filename : ')
if os.path.isfile(fname):
f = open(fname, 'r')
else:
print(fname+' does not exist')
sys.exit()
# Read strings from the file
print('The file contents are: ')
str = f.read()
print(str)
# Closing the file
f.close()
Files
Exercise
Problem- 1
To count number of lines, words and characters in a text file
Problem- 2
To copy an image from one file to another
Files
The with statement
1. Can be used while opening the file
2. It will take care of closing the file, without using close() explicitly
3. Syntax: with open("file_name", "openmode") as fileObj:
Program -1
# With statement to open a file
with open('sample.txt', 'w') as f:
f.write('I am a learnern')
f.write('Python is attactiven')
Program -2
# Using with statement to open a file
with open('sample.txt', 'r') as f:
for line in f:
print(line)
Files
The pickle + Unpickle
1. To store the data of different types, we need to create the class for it.
2. Pickle/Serialization:
- Storing Object into a binary file in the form of bytes.
- Done by a method dump() of pickle module
- pickle.dump(object, file)
3. Unpickle/Deserialization
- Process where byte stream is converted back into the object.
- Object = pickle.load(file)
Files
The pickle: Program
# A python program to create an Emp class witg employee details as instance variables.
# Emp class - save this as Emp.py
class Emp:
def_init_(self, id, name, sal):
self.id = id
self.name = name
self.sal = sal
def display(self):
print("{:5d} {:20s} {:10.2f}".format(self.id, self.name,self.sal))
# pickle - store Emp class object into emp.dat file
import Emp, pickle
# Open emp.dat file as a binary file for writing
f = open('emp.dat', 'wb')
n = int(input('How many employees? '))
for i in range(n):
id = int(input('Enter id: '))
name = input('Enter name: ')
sal = float(input('Enter salary: '))
for i in range(n):
id = int(input('Enter id: '))
name = input('Enter name: ')
sal = float(input('Enter salary: '))
# Create Emp class object
e = Emp.Emp(id, name, sal)
# Store the object e into the file f
pickle.dump(e, f)
#close the file
f.close()
Files
The unpickle: Program
# A python program to create an Emp class witg employee details as instance variables.
# Emp class - save this as Emp.py
class Emp:
def_init_(self, id, name, sal):
self.id = id
self.name = name
self.sal = sal
def display(self):
print("{:5d} {:20s} {:10.2f}".format(self.id, self.name,self.sal))
# unpickle or object de-serialization
import Emp, pickle
# Open the file to read objects
f = open('emp.dat', 'rb')
print('Employees details: ')
while True:
try:
#Read object from file f
obj = pickle.load(f)
# Display the contents of employee obj
obj.display()
except EOFError:
print('End of file reached....')
break
#Close the file
f.close()
Random Binary File Access
using mmap
1. Using mmap, binary data can be viewed as strings
mm = mmap.mmap(f.fileno(), 0)
2. Reading the data using read() and readline()
print(mm.read())
print(mm.readline())
3. We can also retrieve the data using teh slicing operator
print(mm[5: ])
print(mm[5: 10])
4. To modify / replace the data
mm[5: 10] = str
5. To find the first occurrance of the string in the file
n = mm.find(name)
6. To convert name from string to binary string
name = name.encode()
7. To convert bytes into a string
ph = ph.decode()
Demonstrate the code
Zip & Unzip

Zip:

- The file contents are compressed and hence the size will be reduced

- The format of data will be changed making it unreadable
Original
File
Compressed
File
Zipping
Unzipping
Zip & Unzip
Programs
# Zipping the contents of files
from zipfile import *
# create zip file
f = zipfile('test.zip', 'w', 'ZIP_DEFLATED')
# add some files. these are zipped
f.write('file1.txt')
f.write('file2.txt')
f.write('file3.txt')
# close the zip file
print('test.zip file created....')
f.close()
# A Python program to unzip the contents of the files
# that are available in a zip file.
# To view contents of zipped files
from zipfile import*
# open the zip file
z = Zipfile('test.zip', 'r')
# Extract all the file names which are int he zip file
z.extractall()
Working With Directories
Program-1
# A Python program to know the currently working directory.
import os
# get current working directory
current = os.getcwd()
print('Current sirectory= ', current)
Working With Directories
Program-2
# A Python program to create a sub directory and then sub-sun directory in the current
directory.
import os
# create a sub directory by the name mysub
os.mkdir('mysub')
# create a sub-sub directory by the same mysub2
os.mkdir('mysub/mysub2')
Working With Directories
Program-3
# A Python program to use the makedirs() function to create sub and sub-sub directories.
import os
# create sub and sub-sub directories
os.mkdirs('newsub/newsub2')
Working With Directories
Program-4
# A Python program to remove a sub directory that is inside another directory.
import os
# to remove newsub2 directory
os.rmdir('newsub/newsub2')
Working With Directories
Program-5
# A Python program to remove a group of directories in the path
import os
# to remove mysub3, mysub2 and then mysub.
os.removedirs('mysub/mysub2/mysub3')
Working With Directories
Program-6
# A Python program to rename a directory.
import os
# to rename enum as newenum
os.rename('enum', 'newenum')
Working With Directories
Program-7
# A Python program to display all contents of the current directory.
import os
for dirpath, dirnames, filenames in os.walk('.'):
print('Current path: ', dirpath)
print('Directories: ', dirnames)
print('Files: ', filenames)
print()
Running other programs
Program-7
The OS module has the system() method that is useful to run an executableprogram from our
Python program
Example-1
os.system(‘dir’) Display contents of current working DIR
Example-2 os.system(‘python demo.py’) Runs the demo.py code
THANK YOU

More Related Content

What's hot

What is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | EdurekaWhat is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
Edureka!
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
Ashok Raj
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Files in java
Files in javaFiles in java
Python : Data Types
Python : Data TypesPython : Data Types
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
PyData
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
2D Array
2D Array 2D Array
2D Array
Ehatsham Riaz
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Python ppt
Python pptPython ppt
Python ppt
Anush verma
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
 

What's hot (20)

What is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | EdurekaWhat is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Files in java
Files in javaFiles in java
Files in java
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
File in C language
File in C languageFile in C language
File in C language
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
2D Array
2D Array 2D Array
2D Array
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Python ppt
Python pptPython ppt
Python ppt
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 

Similar to Python programming : Files

FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
File Handling in python.docx
File Handling in python.docxFile Handling in python.docx
File Handling in python.docx
manohar25689
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Python File functions
Python File functionsPython File functions
Python File functions
keerthanakommera1
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
Vishal Dutt
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
ssuser00ad4e
 
File handling in Python
File handling in PythonFile handling in Python
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
Sandeepbhuma1
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai saleFile Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
RohitKurdiya1
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
DHARUNESHBOOPATHY
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
files.pptx
files.pptxfiles.pptx
files.pptx
KeerthanaM738437
 

Similar to Python programming : Files (20)

FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
File Handling in python.docx
File Handling in python.docxFile Handling in python.docx
File Handling in python.docx
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
Python File functions
Python File functionsPython File functions
Python File functions
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Python-files
Python-filesPython-files
Python-files
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
 
File handling
File handlingFile handling
File handling
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai saleFile Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
files.pptx
files.pptxfiles.pptx
files.pptx
 

More from Emertxe Information Technologies Pvt Ltd

Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
Emertxe Information Technologies Pvt Ltd
 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf

More from Emertxe Information Technologies Pvt Ltd (20)

premium post (1).pdf
premium post (1).pdfpremium post (1).pdf
premium post (1).pdf
 
Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf
10_isxdigit.pdf
 
01_student_record.pdf
01_student_record.pdf01_student_record.pdf
01_student_record.pdf
 
02_swap.pdf
02_swap.pdf02_swap.pdf
02_swap.pdf
 
01_sizeof.pdf
01_sizeof.pdf01_sizeof.pdf
01_sizeof.pdf
 
07_product_matrix.pdf
07_product_matrix.pdf07_product_matrix.pdf
07_product_matrix.pdf
 
06_sort_names.pdf
06_sort_names.pdf06_sort_names.pdf
06_sort_names.pdf
 
05_fragments.pdf
05_fragments.pdf05_fragments.pdf
05_fragments.pdf
 
04_magic_square.pdf
04_magic_square.pdf04_magic_square.pdf
04_magic_square.pdf
 
03_endianess.pdf
03_endianess.pdf03_endianess.pdf
03_endianess.pdf
 
02_variance.pdf
02_variance.pdf02_variance.pdf
02_variance.pdf
 
01_memory_manager.pdf
01_memory_manager.pdf01_memory_manager.pdf
01_memory_manager.pdf
 
09_nrps.pdf
09_nrps.pdf09_nrps.pdf
09_nrps.pdf
 
11_pangram.pdf
11_pangram.pdf11_pangram.pdf
11_pangram.pdf
 
10_combinations.pdf
10_combinations.pdf10_combinations.pdf
10_combinations.pdf
 
08_squeeze.pdf
08_squeeze.pdf08_squeeze.pdf
08_squeeze.pdf
 
07_strtok.pdf
07_strtok.pdf07_strtok.pdf
07_strtok.pdf
 
06_reverserec.pdf
06_reverserec.pdf06_reverserec.pdf
06_reverserec.pdf
 
05_reverseiter.pdf
05_reverseiter.pdf05_reverseiter.pdf
05_reverseiter.pdf
 

Recently uploaded

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 

Recently uploaded (20)

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 

Python programming : Files

  • 3. Introduction  A file is an object on a computer that stores data, information, settings, or commands used with a computer program  Advantages of files  - Data is stored permanently  - Updation becomes easy  - Data can be shared among various programs  - Huge amount of data can be stored
  • 4. Files Types Text Binary Stores the data in the form of strings Stores data in the form of bytes Example: “Ram” is stored as 3 characters 890.45 is stored as 6 characters Example: “Ram” is stored as 3 bytes 89000.45 is stored as 8 bytes Examples: .txt, .c, .cpp Examples: .jpg, .gif or .png
  • 5. Files Opening a file Name open() Syntax file_handler = open("file_name", "open_mode", "buffering") filename : Name of the file to be opened open_mode: Purpose of opening the file buffering: Used to stored the data temporarily Opening Modes w - To write the data - If file already exist, the data will be lost r - To read the data - The file pointer is positioned at the begining of the file a - To append data to the file - The file pointer is placed at the end of the file w+ - To write and read data - The previous data will be deleted r+ - To read and write - The previous data will not be deleted - The file pointer is placed at the begining of the file a+ - To append and read data - The file pointer will be at the end of the file x - To open the file in exclusive creation mode - The file creation fails, if already file exist Example f = open("myfile.txt", "w") Here, buffer is optional, if omitted 4096 / 8192 bytes will be considered.
  • 6. Files Closing a file Name close() Syntax f.close() Example #Open the file f = open("myfile.txt", "w") #Read the string str = input("Enter the string: ") #Write the string into the file f.write(str) #Close the file f.close()
  • 7. Files Working with text files containing strings To read the content from files, f.read() : Reads all lines, displays line by line f.readlines() : Displays all strings as elements in a list f.read().splitlines(): To suppress the "n" in the list Program #To create a text file to store strings #Open the file f = open("myfile.txt", "r") #Read the data from a file str = f.read() #Reads all data #Display the data print(str) #Close the file f.close() Note: """ f.read(n): Will read 'n' bytes from the file """
  • 8. Files Working with text files containing strings f.seek(offset, fromwhere) - offset : No. of bytes to move - fromwhere : Begining, Current, End - Example : f.seek(10, 0), move file handler from Beg forward 10 bytes. # Appending and then reading strings, Open the file for reading data f = open('myfile.txt', 'a+') print('Enter text to append(@ at end): ') while str != '@': str = input() # accept string into str # Write the string into file if (str != '@'): f.write(str+"n") # Put the file pointer to the beginning of the file f.seek(0,0) # Read strings from the file print('The file cotents are: ') str = f.read() print(str) # Closing the file f.close()
  • 9. Files Knowing If file exists or not Sample: if os.path.isfile(fname): f = open(fname, "r") else: print(fname + "Does not exist") sys.exit() #Terminate the program # Checking if file exists and then reading data import os, sys # open the file for reading data fname = input('Enter filename : ') if os.path.isfile(fname): f = open(fname, 'r') else: print(fname+' does not exist') sys.exit() # Read strings from the file print('The file contents are: ') str = f.read() print(str) # Closing the file f.close()
  • 10. Files Exercise Problem- 1 To count number of lines, words and characters in a text file Problem- 2 To copy an image from one file to another
  • 11. Files The with statement 1. Can be used while opening the file 2. It will take care of closing the file, without using close() explicitly 3. Syntax: with open("file_name", "openmode") as fileObj: Program -1 # With statement to open a file with open('sample.txt', 'w') as f: f.write('I am a learnern') f.write('Python is attactiven') Program -2 # Using with statement to open a file with open('sample.txt', 'r') as f: for line in f: print(line)
  • 12. Files The pickle + Unpickle 1. To store the data of different types, we need to create the class for it. 2. Pickle/Serialization: - Storing Object into a binary file in the form of bytes. - Done by a method dump() of pickle module - pickle.dump(object, file) 3. Unpickle/Deserialization - Process where byte stream is converted back into the object. - Object = pickle.load(file)
  • 13. Files The pickle: Program # A python program to create an Emp class witg employee details as instance variables. # Emp class - save this as Emp.py class Emp: def_init_(self, id, name, sal): self.id = id self.name = name self.sal = sal def display(self): print("{:5d} {:20s} {:10.2f}".format(self.id, self.name,self.sal)) # pickle - store Emp class object into emp.dat file import Emp, pickle # Open emp.dat file as a binary file for writing f = open('emp.dat', 'wb') n = int(input('How many employees? ')) for i in range(n): id = int(input('Enter id: ')) name = input('Enter name: ') sal = float(input('Enter salary: ')) for i in range(n): id = int(input('Enter id: ')) name = input('Enter name: ') sal = float(input('Enter salary: ')) # Create Emp class object e = Emp.Emp(id, name, sal) # Store the object e into the file f pickle.dump(e, f) #close the file f.close()
  • 14. Files The unpickle: Program # A python program to create an Emp class witg employee details as instance variables. # Emp class - save this as Emp.py class Emp: def_init_(self, id, name, sal): self.id = id self.name = name self.sal = sal def display(self): print("{:5d} {:20s} {:10.2f}".format(self.id, self.name,self.sal)) # unpickle or object de-serialization import Emp, pickle # Open the file to read objects f = open('emp.dat', 'rb') print('Employees details: ') while True: try: #Read object from file f obj = pickle.load(f) # Display the contents of employee obj obj.display() except EOFError: print('End of file reached....') break #Close the file f.close()
  • 15. Random Binary File Access using mmap 1. Using mmap, binary data can be viewed as strings mm = mmap.mmap(f.fileno(), 0) 2. Reading the data using read() and readline() print(mm.read()) print(mm.readline()) 3. We can also retrieve the data using teh slicing operator print(mm[5: ]) print(mm[5: 10]) 4. To modify / replace the data mm[5: 10] = str 5. To find the first occurrance of the string in the file n = mm.find(name) 6. To convert name from string to binary string name = name.encode() 7. To convert bytes into a string ph = ph.decode() Demonstrate the code
  • 16. Zip & Unzip  Zip:  - The file contents are compressed and hence the size will be reduced  - The format of data will be changed making it unreadable Original File Compressed File Zipping Unzipping
  • 17. Zip & Unzip Programs # Zipping the contents of files from zipfile import * # create zip file f = zipfile('test.zip', 'w', 'ZIP_DEFLATED') # add some files. these are zipped f.write('file1.txt') f.write('file2.txt') f.write('file3.txt') # close the zip file print('test.zip file created....') f.close() # A Python program to unzip the contents of the files # that are available in a zip file. # To view contents of zipped files from zipfile import* # open the zip file z = Zipfile('test.zip', 'r') # Extract all the file names which are int he zip file z.extractall()
  • 18. Working With Directories Program-1 # A Python program to know the currently working directory. import os # get current working directory current = os.getcwd() print('Current sirectory= ', current)
  • 19. Working With Directories Program-2 # A Python program to create a sub directory and then sub-sun directory in the current directory. import os # create a sub directory by the name mysub os.mkdir('mysub') # create a sub-sub directory by the same mysub2 os.mkdir('mysub/mysub2')
  • 20. Working With Directories Program-3 # A Python program to use the makedirs() function to create sub and sub-sub directories. import os # create sub and sub-sub directories os.mkdirs('newsub/newsub2')
  • 21. Working With Directories Program-4 # A Python program to remove a sub directory that is inside another directory. import os # to remove newsub2 directory os.rmdir('newsub/newsub2')
  • 22. Working With Directories Program-5 # A Python program to remove a group of directories in the path import os # to remove mysub3, mysub2 and then mysub. os.removedirs('mysub/mysub2/mysub3')
  • 23. Working With Directories Program-6 # A Python program to rename a directory. import os # to rename enum as newenum os.rename('enum', 'newenum')
  • 24. Working With Directories Program-7 # A Python program to display all contents of the current directory. import os for dirpath, dirnames, filenames in os.walk('.'): print('Current path: ', dirpath) print('Directories: ', dirnames) print('Files: ', filenames) print()
  • 25. Running other programs Program-7 The OS module has the system() method that is useful to run an executableprogram from our Python program Example-1 os.system(‘dir’) Display contents of current working DIR Example-2 os.system(‘python demo.py’) Runs the demo.py code