SlideShare a Scribd company logo
1 of 17
Python Session - 5
Anirudha Anil Gaikwad
gaikwad.anirudha@gmail.com
What you learn
 Python Modules
 Python Package
 Python File I/O
Python Modules
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for e.g.: filename.py, is called a module and its module name
would be filename.
We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
Python Modules
 How to import modules in Python?
use the import keyword to import modules in Python
>>> import filename
# import statement example
# to import standard module math
import math
print("The value of pi is", math.pi)
Python Modules
 Import with renaming
We can import a module by renaming it as follows.
import calendar as cal
print("------Calendar Program in Python------n");
print("Enter 'x' for exit.");
y = input("Enter Year: ");
if y == 'x':
exit();
else:
m = input("Enter month: ");
yy = int(y);
mm = int(m);
print("n",cal.month(yy,mm))
Python Modules
 Python from...import statement
from used to import specific names from a module without importing the module as a
whole.
# import only pi from math module
from math import pi
print("The value of pi is", pi)
 Import all names
# import all names from the standard module math
from math import *
print("The value of pi is", pi)
Python Package
The packages in python facilitate the developer with the application development
environment by providing a hierarchical directory structure where a package contains
sub-packages, modules, and sub-modules.
A directory must contain a file named __init__.py in order for Python to consider it as a
package. This file can be left empty but we generally place the initialization code for that
package in this file.
Python File I/O
What is a file?
File is a named location on disk to store related information. It is used to permanently
store data in a non-volatile memory (e.g. hard disk).
When we want to read from or write to a file we need to open it first. When we are done,
it needs to be closed
Hence, in Python, a file operation takes place in the following order.
 Open a file
 Read or write (perform operation)
 Close the file
 How to open a file?
Python has a built-in function open() to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/folder/README.txt") # specifying full path
Python File I/O
 The default is reading in text mode. In this mode, we get strings when reading from
the file.
 On the other hand, binary mode returns bytes and this is the mode to be used when
dealing with non-text files like image or exe files.
Python File I/O
Python File I/O
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
f = open("test.txt",mode = 'r',encoding = 'utf-8')
 How to close a file Using Python
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using Python
close() Function
Python File I/O
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
 A safer way is to use a try...finally block.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
Python File I/O
 How to write to File in Python
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first filen")
f.write("This filenn")
f.write("contains three linesn")
How to read files in Python
Python File I/O
>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4) # read the first 4 data
>>> f.read() # read in the rest till end of file
>>> f.tell() # get the current file position
>>> f.seek(0) # bring file cursor to initial position
Python File I/O
Python File I/O
T H A N K S

More Related Content

What's hot (20)

Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Python Interview Questions For Freshers
Python Interview Questions For FreshersPython Interview Questions For Freshers
Python Interview Questions For Freshers
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
Python training
Python trainingPython training
Python training
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
Python
PythonPython
Python
 
PYTHON NOTES
PYTHON NOTESPYTHON NOTES
PYTHON NOTES
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Python advance
Python advancePython advance
Python advance
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python Fundamentals
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
 
Python interview questions for experience
Python interview questions for experiencePython interview questions for experience
Python interview questions for experience
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 

Similar to Python Session - 5

Introduction To Programming with Python-5
Introduction To Programming with Python-5Introduction To Programming with Python-5
Introduction To Programming with Python-5Syed Farjad Zia Zaidi
 
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
 
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!
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdfRashmiAngane1
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxAshwini Raut
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdfsulekha24
 
python , it contains introduction to text files , and many more
python , it contains introduction to text files , and many morepython , it contains introduction to text files , and many more
python , it contains introduction to text files , and many moreMOHAMMADAfricawala
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptxAmitKaur17
 

Similar to Python Session - 5 (20)

Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
Introduction To Programming with Python-5
Introduction To Programming with Python-5Introduction To Programming with Python-5
Introduction To Programming with Python-5
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
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.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
Python-files
Python-filesPython-files
Python-files
 
Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
 
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 |...
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
files.pptx
files.pptxfiles.pptx
files.pptx
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
python , it contains introduction to text files , and many more
python , it contains introduction to text files , and many morepython , it contains introduction to text files , and many more
python , it contains introduction to text files , and many more
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Recently uploaded (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Python Session - 5

  • 1. Python Session - 5 Anirudha Anil Gaikwad gaikwad.anirudha@gmail.com
  • 2. What you learn  Python Modules  Python Package  Python File I/O
  • 3. Python Modules Modules refer to a file containing Python statements and definitions. A file containing Python code, for e.g.: filename.py, is called a module and its module name would be filename. We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code. We can define our most used functions in a module and import it, instead of copying their definitions into different programs.
  • 4. Python Modules  How to import modules in Python? use the import keyword to import modules in Python >>> import filename # import statement example # to import standard module math import math print("The value of pi is", math.pi)
  • 5. Python Modules  Import with renaming We can import a module by renaming it as follows. import calendar as cal print("------Calendar Program in Python------n"); print("Enter 'x' for exit."); y = input("Enter Year: "); if y == 'x': exit(); else: m = input("Enter month: "); yy = int(y); mm = int(m); print("n",cal.month(yy,mm))
  • 6. Python Modules  Python from...import statement from used to import specific names from a module without importing the module as a whole. # import only pi from math module from math import pi print("The value of pi is", pi)  Import all names # import all names from the standard module math from math import * print("The value of pi is", pi)
  • 7. Python Package The packages in python facilitate the developer with the application development environment by providing a hierarchical directory structure where a package contains sub-packages, modules, and sub-modules. A directory must contain a file named __init__.py in order for Python to consider it as a package. This file can be left empty but we generally place the initialization code for that package in this file.
  • 8. Python File I/O What is a file? File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g. hard disk). When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed Hence, in Python, a file operation takes place in the following order.  Open a file  Read or write (perform operation)  Close the file
  • 9.  How to open a file? Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. >>> f = open("test.txt") # open file in current directory >>> f = open("C:/folder/README.txt") # specifying full path Python File I/O  The default is reading in text mode. In this mode, we get strings when reading from the file.  On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.
  • 11. Python File I/O f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp",'r+b') # read and write in binary mode f = open("test.txt",mode = 'r',encoding = 'utf-8')
  • 12.  How to close a file Using Python When we are done with operations to the file, we need to properly close the file. Closing a file will free up the resources that were tied with the file and is done using Python close() Function Python File I/O f = open("test.txt",encoding = 'utf-8') # perform file operations f.close()  A safer way is to use a try...finally block. try: f = open("test.txt",encoding = 'utf-8') # perform file operations finally: f.close()
  • 13. Python File I/O  How to write to File in Python with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first filen") f.write("This filenn") f.write("contains three linesn")
  • 14. How to read files in Python Python File I/O >>> f = open("test.txt",'r',encoding = 'utf-8') >>> f.read(4) # read the first 4 data >>> f.read() # read in the rest till end of file >>> f.tell() # get the current file position >>> f.seek(0) # bring file cursor to initial position
  • 17. T H A N K S