SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
Mr. Vikram Singh Slathia
 
Python by Rj
Python by RjPython by Rj
Python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Python Interview Questions For Freshers
Python Interview Questions For FreshersPython Interview Questions For Freshers
Python Interview Questions For Freshers
zynofustechnology
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
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
Jaganadh Gopinadhan
 
Python training
Python trainingPython training
Python training
Kunalchauhan76
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
Mohd Sajjad
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
Sumit Satam
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
Kamal Acharya
 
Python
PythonPython
Python
Rural Engineering College Hulkoti
 
PYTHON NOTES
PYTHON NOTESPYTHON NOTES
PYTHON NOTES
Ni
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
Haitham El-Ghareeb
 
Python advance
Python advancePython advance
Python advance
Deepak Chandella
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
Dozie Agbo
 
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
Praveen M Jigajinni
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
RajKumar Rampelli
 
Python interview questions for experience
Python interview questions for experiencePython interview questions for experience
Python interview questions for experience
MYTHILIKRISHNAN4
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
Saraswathi Murugan
 

Similar to Python Session - 5 (20)

Master of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdfMaster of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdf
Krrai1
 
Using python libraries.pptx , easy ppt to study class 12
Using python libraries.pptx , easy ppt to study class 12Using python libraries.pptx , easy ppt to study class 12
Using python libraries.pptx , easy ppt to study class 12
anikedheikhamsingh
 
Python File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptxPython File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptx
saiwww3841k
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
Introduction To Programming with Python-5
Introduction To Programming with Python-5Introduction To Programming with Python-5
Introduction To Programming with Python-5
Syed Farjad Zia Zaidi
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
4HG19EC010HARSHITHAH
 
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.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
Karudaiyar Ganapathy
 
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!
 
File handling for reference class 12.pptx
File handling for reference class 12.pptxFile handling for reference class 12.pptx
File handling for reference class 12.pptx
PreeTVithule1
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
RashmiAngane1
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
22261A1201ABDULMUQTA
 
files.pptx
files.pptxfiles.pptx
files.pptx
KeerthanaM738437
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
Praveen M Jigajinni
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
nishant874609
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Master of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdfMaster of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdf
Krrai1
 
Using python libraries.pptx , easy ppt to study class 12
Using python libraries.pptx , easy ppt to study class 12Using python libraries.pptx , easy ppt to study class 12
Using python libraries.pptx , easy ppt to study class 12
anikedheikhamsingh
 
Python File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptxPython File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptx
saiwww3841k
 
Introduction To Programming with Python-5
Introduction To Programming with Python-5Introduction To Programming with Python-5
Introduction To Programming with Python-5
Syed 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!
 
File handling for reference class 12.pptx
File handling for reference class 12.pptxFile handling for reference class 12.pptx
File handling for reference class 12.pptx
PreeTVithule1
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
RashmiAngane1
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Ad

Recently uploaded (20)

What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
Artificial hand using embedded system.pptx
Artificial hand using embedded system.pptxArtificial hand using embedded system.pptx
Artificial hand using embedded system.pptx
bhoomigowda12345
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
Ad

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
  翻译: