SlideShare a Scribd company logo
2
Most read
3
Most read
9
Most read
Files in Python
File handling in Python involves interacting with files on your computer to read
data from them or write data to them.
Python provides several built-in functions and methods for creating, opening,
reading, writing, and closing files.
TYPES OF FILES
Computers store every file as a collection of 0 s and 1 s i.e., in binary form.
Therefore, every file is basically just a series of bytes stored one after the other.
There are mainly two types of data files –
1. text file
2. binary file
A text file consists of human readable characters, which can be opened by any text
editor. On the other hand, binary files are made up of non-human readable
characters and symbols, which require specific programs to access its contents.
Text file
• A text file can be understood as a sequence of characters consisting of alphabets,
numbers and other special symbols.
• Files with extensions like .txt, json, html,xml,csv, etc. are some examples of text files.
• When we open a text file using a text editor (e.g., Notepad), we see several lines of
text.
Binary Files
• Binary files are also stored in terms of bytes (0s and 1s), but unlike text files, these
bytes do not represent the ASCII values of characters.
• Rather, they represent the actual content such as image, audio, video, compressed
versions of other files, executable files, etc.
• These files are not human readable. Thus, trying to open a binary file using a text
editor will show some garbage values.
• We need specific software to read or write the contents of a binary file.
OPENING AND CLOSING A TEXT FILE
• In real world applications, computer programs deal with data coming from
different sources like databases, CSV files, HTML, XML, JSON, etc.
• We broadly access files either to write or read data from it.
• But operations on files include creating and opening a file, writing data in
a file, traversing a file, reading data from a file and so on
r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of
the file. This is the default mode.
r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file
w
Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
wbOpens a file for writing only in binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing.
w+
Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and
writing.
wb+
Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.
a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is
in the append mode. If the file does not exist, it creates a new file for writing.
ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does not exist, it creates a new file for reading and
writing.
ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the file
if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
• # Opening a file in read mode
file = open("example.txt", "r")
• # Opening a file in write mode
file = open("example.txt", "w")
• # Opening a file in append mode
file = open("example.txt", "a")
• # Opening a file in binary read mode
file = open("example.txt", "rb")
Reading a File in Python
Reading a file in Python involves opening the file in a mode that allows for
reading, and then using various methods to extract the data from the file.
Python provides several methods to read data from a file −
read() − Reads the entire file.
readline() − Reads one line at a time.
readlines − Reads all lines into a list.
Example:
with open("avnt.txt", "r") as file:
content = file.read()
print(content)
file = open("avnt.txt", "r")
content = file.read()
print(content)
file.close()
Using readline() method
In here, we are using the readline() method to read one line at a time,
making it memory efficient for reading large files line by line
with open("avnt.txt", "r") as file:
line = file.readline()
while line:
print(line, end='')
line = file.readline()
Using readlines() method
Now, we are using the readlines() method to read the entire file and splits it
into a list where each element is a line
with open("avnt.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line, end='')
Writing to a File in Python
Writing to a file in Python involves opening the file in a mode that allows
writing, and then using various methods to add content to the file.
To write data to a file, use the write() or writelines() methods.
When opening a file in write mode ('w'), the file's existing content is erased.
file = open("avnt.txt", "w")
file.write("Hello, World!")
file.close()
Using the write() method
In this example, we are using the write() method to write the string passed
to it to the file.
If the file is opened in 'w' mode, it will overwrite any existing content.
If the file is opened in 'a' mode, it will append the string to the end of the
file −
with open("avnt.txt", "w") as file:
file.write("Hello, World!")
print ("Content added Successfully!!")
Using the writelines() method
In here, we are using the writelines() method to take a list of strings and
writes each string to the file.
It is useful for writing multiple lines at once −
lines = ["First linen", "Second linen", "Third linen"]
with open("avnt.txt", "w") as file:
file.writelines(lines)
print ("Content added Successfully!!")
Closing a File
Closing a file is essential to ensure that all resources used by the file are
properly released. file.close() method closes the file and ensures that any
changes made to the file are saved.
file = open("avnt.txt", "r")
# Perform file operations
file.close()
Handling Exceptions When Closing a File
It's important to handle exceptions to ensure that files are closed properly,
even if an error occurs during file operations.
try:
file = open(“avnt.txt", "r")
content = file.read()
print(content)
finally:
file.close()
Advantages of File Handling in Python
Versatility : File handling in Python allows us to perform a wide range of
operations, such as creating, reading, writing, appending, renaming and
deleting files.
Flexibility : File handling in Python is highly flexible, as it allows us to work with
different file types (e.g. text files, binary files, CSV files , etc.) and to perform
different operations on files (e.g. read, write, append, etc.).
User - friendly : Python provides a user-friendly interface for file handling,
making it easy to create, read and manipulate files.
Cross-platform : Python file-handling functions work across different platforms
(e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.
Disadvantages of File Handling in Python
Error-prone: File handling operations in Python can be prone to errors,
especially if the code is not carefully written or if there are issues with the file
system (e.g. file permissions, file locks, etc.).
Security risks : File handling in Python can also pose security risks, especially
if the program accepts user input that can be used to access or modify
sensitive files on the system.
Complexity : File handling in Python can be complex, especially when working
with more advanced file formats or operations. Careful attention must be
paid to the code to

More Related Content

PPTX
Regular expressions,function and glob module.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
PPTX
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
PPTX
JSON, XML and Data Science introduction.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
DOCX
Python Notes for mca i year students osmania university.docx
Ramakrishna Reddy Bijjam
 
PDF
File handling in Python
BMS Institute of Technology and Management
 
PPTX
File Handling Python
Akhil Kaushik
 
Regular expressions,function and glob module.pptx
Ramakrishna Reddy Bijjam
 
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
JSON, XML and Data Science introduction.pptx
Ramakrishna Reddy Bijjam
 
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
Python Notes for mca i year students osmania university.docx
Ramakrishna Reddy Bijjam
 
File Handling Python
Akhil Kaushik
 

What's hot (20)

PDF
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
PPTX
Python Strings.pptx
M Vishnuvardhan Reddy
 
PPTX
Basics of python
Jatin Kochhar
 
PPTX
Data file handling in python introduction,opening & closing files
keeeerty
 
PPTX
Json
Steve Fort
 
PPTX
Boolean and conditional logic in Python
gsdhindsa
 
PDF
Overview of python 2019
Samir Mohanty
 
PPTX
django
Mohamed Essam
 
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
PPTX
Fundamentals of Python Programming
Kamal Acharya
 
PPTX
Full Python in 20 slides
rfojdar
 
PPTX
How to download and install Python - lesson 2
Shohel Rana
 
PPTX
Introduction to PHP
Collaboration Technologies
 
PPT
Introduction to Python
amiable_indian
 
PPT
Exception handling and function in python
TMARAGATHAM
 
PPTX
Uploading a file with php
Muhamad Al Imran
 
PPTX
Files in Python.pptx
Koteswari Kasireddy
 
PPTX
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
PDF
Python file handling
Prof. Dr. K. Adisesha
 
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Python Strings.pptx
M Vishnuvardhan Reddy
 
Basics of python
Jatin Kochhar
 
Data file handling in python introduction,opening & closing files
keeeerty
 
Boolean and conditional logic in Python
gsdhindsa
 
Overview of python 2019
Samir Mohanty
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
Fundamentals of Python Programming
Kamal Acharya
 
Full Python in 20 slides
rfojdar
 
How to download and install Python - lesson 2
Shohel Rana
 
Introduction to PHP
Collaboration Technologies
 
Introduction to Python
amiable_indian
 
Exception handling and function in python
TMARAGATHAM
 
Uploading a file with php
Muhamad Al Imran
 
Files in Python.pptx
Koteswari Kasireddy
 
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
 
Python file handling
Prof. Dr. K. Adisesha
 
Ad

Similar to What is FIle and explanation of text files.pptx (20)

PPT
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
PDF
23CS101T PSPP python program - UNIT 5.pdf
RajeshThanikachalam
 
PPTX
this is about file concepts in class 12 in python , text file, binary file, c...
Primary2Primary2
 
PDF
03-01-File Handling.pdf
botin17097
 
PPTX
Files in Python.pptx
Koteswari Kasireddy
 
PPTX
pspp-rsk.pptx
ARYAN552812
 
PDF
File handling and Dictionaries in python
nitamhaske
 
PDF
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
PDF
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
PPTX
file handling.pptx avlothaan pa thambi popa
senniyappanharish
 
PPTX
FILE HANDLING IN PYTHON Presentation Computer Science
HargunKaurGrover
 
PDF
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 
PDF
File handling4.pdf
sulekha24
 
PPTX
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
samkinggraphics19
 
PPTX
5-filehandling-2004054567151830 (1).pptx
lionsconvent1234
 
PPTX
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
PPTX
file_handling_python_bca_computer_python
hansibansal
 
PPTX
File handling for reference class 12.pptx
PreeTVithule1
 
PDF
File handling3.pdf
nishant874609
 
PPTX
03-01-File Handling python.pptx
qover
 
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
23CS101T PSPP python program - UNIT 5.pdf
RajeshThanikachalam
 
this is about file concepts in class 12 in python , text file, binary file, c...
Primary2Primary2
 
03-01-File Handling.pdf
botin17097
 
Files in Python.pptx
Koteswari Kasireddy
 
pspp-rsk.pptx
ARYAN552812
 
File handling and Dictionaries in python
nitamhaske
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
file handling.pptx avlothaan pa thambi popa
senniyappanharish
 
FILE HANDLING IN PYTHON Presentation Computer Science
HargunKaurGrover
 
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 
File handling4.pdf
sulekha24
 
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
samkinggraphics19
 
5-filehandling-2004054567151830 (1).pptx
lionsconvent1234
 
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
file_handling_python_bca_computer_python
hansibansal
 
File handling for reference class 12.pptx
PreeTVithule1
 
File handling3.pdf
nishant874609
 
03-01-File Handling python.pptx
qover
 
Ad

More from Ramakrishna Reddy Bijjam (20)

PPTX
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
DOCX
VBS control structures for if do whilw.docx
Ramakrishna Reddy Bijjam
 
DOCX
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 
DOCX
VBScript Functions procedures and arrays.docx
Ramakrishna Reddy Bijjam
 
DOCX
VBScript datatypes and control structures.docx
Ramakrishna Reddy Bijjam
 
PPTX
Numbers and global functions conversions .pptx
Ramakrishna Reddy Bijjam
 
DOCX
Structured Graphics in dhtml and active controls.docx
Ramakrishna Reddy Bijjam
 
DOCX
Filters and its types as wave shadow.docx
Ramakrishna Reddy Bijjam
 
PPTX
JavaScript Arrays and its types .pptx
Ramakrishna Reddy Bijjam
 
PPTX
JS Control Statements and Functions.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Code conversions binary to Gray vice versa.pptx
Ramakrishna Reddy Bijjam
 
PDF
FIXED and FLOATING-POINT-REPRESENTATION.pdf
Ramakrishna Reddy Bijjam
 
PPTX
Handling Missing Data for Data Analysis.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Data Frame Data structure in Python pandas.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Series data structure in Python Pandas.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Mongodatabase with Python for Students.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Arrays to arrays and pointers with arrays.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Python With MongoDB in advanced Python.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Certinity Factor and Dempster-shafer theory .pptx
Ramakrishna Reddy Bijjam
 
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
VBS control structures for if do whilw.docx
Ramakrishna Reddy Bijjam
 
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 
VBScript Functions procedures and arrays.docx
Ramakrishna Reddy Bijjam
 
VBScript datatypes and control structures.docx
Ramakrishna Reddy Bijjam
 
Numbers and global functions conversions .pptx
Ramakrishna Reddy Bijjam
 
Structured Graphics in dhtml and active controls.docx
Ramakrishna Reddy Bijjam
 
Filters and its types as wave shadow.docx
Ramakrishna Reddy Bijjam
 
JavaScript Arrays and its types .pptx
Ramakrishna Reddy Bijjam
 
JS Control Statements and Functions.pptx
Ramakrishna Reddy Bijjam
 
Code conversions binary to Gray vice versa.pptx
Ramakrishna Reddy Bijjam
 
FIXED and FLOATING-POINT-REPRESENTATION.pdf
Ramakrishna Reddy Bijjam
 
Handling Missing Data for Data Analysis.pptx
Ramakrishna Reddy Bijjam
 
Data Frame Data structure in Python pandas.pptx
Ramakrishna Reddy Bijjam
 
Series data structure in Python Pandas.pptx
Ramakrishna Reddy Bijjam
 
Mongodatabase with Python for Students.pptx
Ramakrishna Reddy Bijjam
 
Arrays to arrays and pointers with arrays.pptx
Ramakrishna Reddy Bijjam
 
Python With MongoDB in advanced Python.pptx
Ramakrishna Reddy Bijjam
 
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
Certinity Factor and Dempster-shafer theory .pptx
Ramakrishna Reddy Bijjam
 

Recently uploaded (20)

PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PDF
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
DOCX
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PPTX
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 

What is FIle and explanation of text files.pptx

  • 1. Files in Python File handling in Python involves interacting with files on your computer to read data from them or write data to them. Python provides several built-in functions and methods for creating, opening, reading, writing, and closing files. TYPES OF FILES Computers store every file as a collection of 0 s and 1 s i.e., in binary form. Therefore, every file is basically just a series of bytes stored one after the other. There are mainly two types of data files – 1. text file 2. binary file A text file consists of human readable characters, which can be opened by any text editor. On the other hand, binary files are made up of non-human readable characters and symbols, which require specific programs to access its contents.
  • 2. Text file • A text file can be understood as a sequence of characters consisting of alphabets, numbers and other special symbols. • Files with extensions like .txt, json, html,xml,csv, etc. are some examples of text files. • When we open a text file using a text editor (e.g., Notepad), we see several lines of text. Binary Files • Binary files are also stored in terms of bytes (0s and 1s), but unlike text files, these bytes do not represent the ASCII values of characters. • Rather, they represent the actual content such as image, audio, video, compressed versions of other files, executable files, etc. • These files are not human readable. Thus, trying to open a binary file using a text editor will show some garbage values. • We need specific software to read or write the contents of a binary file.
  • 3. OPENING AND CLOSING A TEXT FILE • In real world applications, computer programs deal with data coming from different sources like databases, CSV files, HTML, XML, JSON, etc. • We broadly access files either to write or read data from it. • But operations on files include creating and opening a file, writing data in a file, traversing a file, reading data from a file and so on
  • 4. r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file
  • 5. w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. wbOpens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
  • 6. a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
  • 7. • # Opening a file in read mode file = open("example.txt", "r") • # Opening a file in write mode file = open("example.txt", "w") • # Opening a file in append mode file = open("example.txt", "a") • # Opening a file in binary read mode file = open("example.txt", "rb")
  • 8. Reading a File in Python Reading a file in Python involves opening the file in a mode that allows for reading, and then using various methods to extract the data from the file. Python provides several methods to read data from a file − read() − Reads the entire file. readline() − Reads one line at a time. readlines − Reads all lines into a list. Example: with open("avnt.txt", "r") as file: content = file.read() print(content)
  • 9. file = open("avnt.txt", "r") content = file.read() print(content) file.close()
  • 10. Using readline() method In here, we are using the readline() method to read one line at a time, making it memory efficient for reading large files line by line with open("avnt.txt", "r") as file: line = file.readline() while line: print(line, end='') line = file.readline()
  • 11. Using readlines() method Now, we are using the readlines() method to read the entire file and splits it into a list where each element is a line with open("avnt.txt", "r") as file: lines = file.readlines() for line in lines: print(line, end='')
  • 12. Writing to a File in Python Writing to a file in Python involves opening the file in a mode that allows writing, and then using various methods to add content to the file. To write data to a file, use the write() or writelines() methods. When opening a file in write mode ('w'), the file's existing content is erased. file = open("avnt.txt", "w") file.write("Hello, World!") file.close()
  • 13. Using the write() method In this example, we are using the write() method to write the string passed to it to the file. If the file is opened in 'w' mode, it will overwrite any existing content. If the file is opened in 'a' mode, it will append the string to the end of the file − with open("avnt.txt", "w") as file: file.write("Hello, World!") print ("Content added Successfully!!")
  • 14. Using the writelines() method In here, we are using the writelines() method to take a list of strings and writes each string to the file. It is useful for writing multiple lines at once − lines = ["First linen", "Second linen", "Third linen"] with open("avnt.txt", "w") as file: file.writelines(lines) print ("Content added Successfully!!")
  • 15. Closing a File Closing a file is essential to ensure that all resources used by the file are properly released. file.close() method closes the file and ensures that any changes made to the file are saved. file = open("avnt.txt", "r") # Perform file operations file.close()
  • 16. Handling Exceptions When Closing a File It's important to handle exceptions to ensure that files are closed properly, even if an error occurs during file operations. try: file = open(“avnt.txt", "r") content = file.read() print(content) finally: file.close()
  • 17. Advantages of File Handling in Python Versatility : File handling in Python allows us to perform a wide range of operations, such as creating, reading, writing, appending, renaming and deleting files. Flexibility : File handling in Python is highly flexible, as it allows us to work with different file types (e.g. text files, binary files, CSV files , etc.) and to perform different operations on files (e.g. read, write, append, etc.). User - friendly : Python provides a user-friendly interface for file handling, making it easy to create, read and manipulate files. Cross-platform : Python file-handling functions work across different platforms (e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.
  • 18. Disadvantages of File Handling in Python Error-prone: File handling operations in Python can be prone to errors, especially if the code is not carefully written or if there are issues with the file system (e.g. file permissions, file locks, etc.). Security risks : File handling in Python can also pose security risks, especially if the program accepts user input that can be used to access or modify sensitive files on the system. Complexity : File handling in Python can be complex, especially when working with more advanced file formats or operations. Careful attention must be paid to the code to