0% found this document useful (0 votes)
25 views21 pages

Python File Handling Basics Guide

The document provides an overview of file handling in Python, including how to open, close, read, and write files using built-in functions and methods. It explains the use of the open() function, file object attributes, and the importance of the close() method, along with examples of reading and writing data. Additionally, it covers renaming and deleting files using the os module.

Uploaded by

ssuresh19747745
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views21 pages

Python File Handling Basics Guide

The document provides an overview of file handling in Python, including how to open, close, read, and write files using built-in functions and methods. It explains the use of the open() function, file object attributes, and the importance of the close() method, along with examples of reading and writing data. Additionally, it covers renaming and deleting files using the os module.

Uploaded by

ssuresh19747745
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Python

Programming
File Handling in
Python
Learning
outcomes:
• File Handling
• Opening and Closing Files
• The open Function
• The file Object Attributes
• The close() Method
• Reading and Writing Files
• The write() and write() Methods
• MORE OPERATIONS ON FILEs
File Handling
File handling in Python refers to the manipulation of
files, which involves reading from and writing to files.
Python provides built-in functions and methods for
performing various file-related operations.
Python supports file handling and allows users to
handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
The concept of file handling has stretched over various
other languages, but the implementation is either
complicated or lengthy, like other concepts of Python,
this concept here is also easy and short.
Opening and Closing Files
Until now, you have been reading and writing to
the standard input and output. Now, we will see
how to use actual data files.
Python provides basic functions and methods
necessary to manipulate files by default. You can do
your most of the file manipulation using a file
object.
When working with files, you need to
specify the mode in which you want to
open the file.
The open Function
Before you can read or write a file, you have to
open it using Python's built-in open() function. This
function creates a file object, which would be
utilized to call other support methods associated
with it. We use open() function in Python to open a
file in read or write mode.
Syntax :
file object = open(file_name [, access_mode][,
buffering])
The open Function
Here are parameter details:
file_name: The file_name argument is a string
value that contains the name of the file that you
want to access.
access_mode: The access_mode determines the
mode in which the file has to be opened, i.e., read,
write, append, etc.
“ r “, for reading.
“ w “, for writing.
“ a “, for appending.
“ r+ “, for both reading and writing
“ab” for appending in binary format
The open Function
“rb“ for reading only in binary format
“rb+“ for both reading and writing in binary format
“wb “ for writing only in binary format
“w+” for both reading and writing
“wb+“for both reading and writing in binary format
One must keep in mind that the mode argument is not
mandatory. If not passed, then Python will assume it to be
“ r ” by default.
Buffering(Optional): If the buffering value is set to 0, no
buffering takes place. If the buffering value is 1, line buffering
is performed while accessing a file. If you specify the buffering
value as an integer greater than 1, then buffering action is
performed with the indicated buffer size. If negative, the
buffer size is the system default (default behavior).
The open Function
Example:
"r" (Read): Opens the file for reading. Raises an error if the
file does not exist.

file = open(“[Link]", "r")

"w" (Write): Opens the file for writing. If the file already
exists, its contents are truncated. If the file doesn't exist, a
new file is created.

file1 = open(“[Link]", "w")


The file Object Attributes
Once a file is opened and you have one file object,
you can get various information related to that file.
Here is a list of all attributes related to file object:
[Link] : Returns true if file is closed, false
otherwise.
[Link] : Returns access mode with which file
was opened.
[Link] : Returns name of the file.
[Link] : Returns false if space explicitly
required with print, true otherwise.
The close() Method
The close() method of a file object flushes any
unwritten information and closes the file object,
after which no more writing can be done.
Python automatically closes a file when the
reference object of a file is reassigned to another
file. It is a good practice to use the close() method
to close a file.
Syntax :

[Link]();
Reading and Writing Files
The file object provides a set of access methods to
make our lives easier. We would see how to use
read() and write() methods to read and write files.
read(): Reads the entire content of the file.
write(data): Writes the specified data to the file.
The read() Method
The read() method reads a string from an open file.
It is important to note that Python strings can have
binary data, apart from text data.
Syntax
[Link]([count]);

Here, passed parameter is the number of bytes to


be read from the opened file. This method starts
reading from the beginning of the file and if count
is missing, then it tries to read till the end of file.
The write() Method
The write() method writes any string to an open
file. It is important to note that Python strings can
have binary data and not just text.
The write() method does not add a newline
character ('\n') to the end of the string:
Syntax
[Link](string);
Examples:
Till now we have seen the theoretical concept of
file I/O.
Now its time for us to write the program for files in
python.
Example: Reading entire content from the file.

file = open("[Link]", "r")


content = [Link]()
print(content)
Examples:
Example: Writing data to the file.
F = open("[Link]", 'w')
[Link]("Hello, Good Morning")
[Link]()
Example: Opens the file for writing, but
appends new data to the end of the file
instead of truncating it.
file = open("[Link]", "a")
[Link]("I am fine. Thank you!")
[Link]()
Using with Statement
A better practice is to use the with statement,
known as a context manager. It automatically
closes the file when the code block is exited.
Here's an example of reading and writing
to a file:
with open("[Link]", "w") as file:
[Link]("Hello, World!\n")
[Link]("This is a sample file.")

with open("[Link]", "r") as file:


content = [Link]()
print(content)
Renaming and Deleting Files
Python os module provides methods that help you
perform file-processing operations, such as
renaming and deleting files.
To use this module you need to import it first and
then you can call any related functions.
Renaming and Deleting Files
rename() Method :
The rename() method takes two arguments, the
current filename and the new filename.
Syntax
[Link](current_file_name, new_file_name)

Example:
import os
# Rename a file from [Link] to [Link]
[Link]( " [Link] ", " [Link] " )
Renaming and Deleting Files
remove() Method :
You can use the remove() method to delete files by
supplying the name of the file to be deleted as the
argument.
Syntax :
[Link](file_name)

Example:
import os
# Delete file [Link]
[Link](“[Link]")
Thank you

You might also like