0% found this document useful (0 votes)
6 views

Python File Handling

This document provides an overview of file handling in Python, detailing how to open, read, write, and close files using various modes. It explains the use of the open() function, the importance of closing files, and methods for reading file content, including reading lines and looping through files. Additionally, it covers creating new files, using the 'with' statement for file operations, and basic file management tasks like renaming and removing files.

Uploaded by

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

Python File Handling

This document provides an overview of file handling in Python, detailing how to open, read, write, and close files using various modes. It explains the use of the open() function, the importance of closing files, and methods for reading file content, including reading lines and looping through files. Additionally, it covers creating new files, using the 'with' statement for file operations, and basic file management tasks like renaming and removing files.

Uploaded by

Fawaz Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Python File Handling

Opening a file
Python provides the open() function which accepts two arguments, file name and access mode in which the file is
accessed. The function returns a file object which can be used to perform various operations like reading, writing,
etc.

The syntax to use the open() function is given below.

1. file object = open(<file-name>, <access-mode>, <buffering>)

Python File Modes

Mode Description

'r' Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates the file if it
'w'
exists.

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

Open for appending at the end of the file without truncating it. Creates a new file if it
'a'
does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

Here is a list of all attributes related to file object −

Sr.No. Attribute & Description

1
file.closed

Returns true if file is closed, false otherwise.


2
file.mode

Returns access mode with which file was opened.

3
file.name

Returns name of the file.

4
file.softspace

Returns false if space explicitly required with print, true otherwise.

Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read mode and
printing its content on the console.

Example
#opens the file file.txt in read mode
fileptr = open("file.txt","r")

if fileptr:
print("file is opened successfully")

The close() method


Once all the operations are done on the file, we must close it through our python script using the close() method.
Any unwritten information gets destroyed once the close() method is called on a file object.

Example
# opens the file file.txt in read mode
fileptr = open("file.txt","r")

if fileptr:
print("file is opened successfully")

#closes the opened file


fileptr.close()
Reading the file
To read a file using the python script, the python provides us the read() method. The read() method reads a string
from the file. It can read the data in the text as well as binary format.

#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");

#stores all the data of the file into the variable content
content = fileptr.read(9);

# prints the type of the data stored in the file


print(type(content))

#prints the content of the file


print(content)

#closes the opened file


fileptr.close()

Read Lines of the file


Python facilitates us to read the file line by line by using a function readline(). The readline() method reads the lines
of the file from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of
the file.

Consider the following example which contains a function readline() that reads the first line of our
file "file.txt" containing three lines.

Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");

#stores all the data of the file into the variable content
content = fileptr.readline();

# prints the type of the data stored in the file


print(type(content))

#prints the content of the file


print(content)
#closes the opened file
fileptr.close()

Looping through the file


By looping through the lines of the file, we can read the whole file.

Example
#open the file.txt in read mode. causes an error if no such file exists.

fileptr = open("file.txt","r");

#running a for loop


for i in fileptr:
print(i) # i contains each line of the file

Writing the file


To write some text to a file, we need to open the file using the open method with one of the following access modes.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file exists.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.

Consider the following example.

Example 1
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");

#appending the content to the file


fileptr.write("Python is the modern day language. It makes things so simple.")

#closing the opened file


fileptr.close();

Example 2
#open the file.txt in write mode.
fileptr = open("file.txt","w");

#overwriting the content of the file


fileptr.write("Python is the modern day language. It makes things so simple.")

#closing the opened file


fileptr.close();

Python File Handling


Till now, we were taking the input from the console and writing it back to the console to interact with the user.

Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited a
displayed on the console, and since the memory is volatile, it is impossible to recover the programmatically generated data again an

However, if we need to do so, we may store it onto the local file system which is volatile and can be accessed every time. Here, com
handling.

In this section of the tutorial, we will learn all about file handling in python including, creating a file, opening a file, closing a file, w
file, etc.

Opening a file
Python provides the open() function which accepts two arguments, file name and access mode in which the file is accessed. The fun
which can be used to perform various operations like reading, writing, etc.

The syntax to use the open() function is given below.

1. file object = open(<file-name>, <access-mode>, <buffering>)

The files can be accessed using various modes like read, write, or append. The following are the details about the access mode to op

SN Access Description
mode

1 R It opens the file to read-only. The file pointer exists at the beginning. The file is by default

open in this mode if no access mode is passed.

2 Rb It opens the file to read only in binary format. The file pointer exists at the beginning of the file.
3 r+ It opens the file to read and write both. The file pointer exists at the beginning of the file.

4 rb+ It opens the file to read and write both in binary format. The file pointer exists at the beginning

of the file.

5 W It opens the file to write only. It overwrites the file if previously exists or creates a new one if no

file exists with the same name. The file pointer exists at the beginning of the file.

6 Wb It opens the file to write only in binary format. It overwrites the file if it exists previously

or creates a new one if no file exists with the same name. The file pointer exists at the beginning of

7 w+ It opens the file to write and read both. It is different from r+ in the sense that it overwrites the prev
whereas r+ doesn?t overwrite the previously written file. It creates a new file if no file exists. The fi
beginning of the file.

8 wb+ It opens the file to write and read both in binary format. The file pointer exists at the beginning of th

9 A It opens the file in the append mode. The file pointer exists at the end of the previously written file
new file if no file exists with the same name.

1 Ab It opens the file in the append mode in binary format. The pointer exists at the end of the previously
0 new file in binary format if no file exists with the same name.

1 a+ It opens a file to append and read both. The file pointer remains at the end of the file if a file exists.
1 file exists with the same name.

1 ab+ It opens a file to append and read both in binary format. The file pointer remains at the end of the fi
2

Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read mode and printing its content o

Example
#opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")

Output:

<class '_io.TextIOWrapper'>

file is opened successfully

The close() method


Once all the operations are done on the file, we must close it through our python script using the close() method. Any unwritten info
once the close() method is called on a file object.

We can perform any operation on the file externally in the file system is the file is opened in python, hence it is good practice to clo
operations are done.

The syntax to use the close() method is given below.

1. fileobject.close()

Consider the following example.

Example
# opens the file file.txt in read mode
fileptr = open("file.txt","r")

if fileptr:
print("file is opened successfully")

#closes the opened file


fileptr.close()

Reading the file


To read a file using the python script, the python provides us the read() method. The read() method reads a string from the file.

It can read the data in the text as well as binary format.

The syntax of the read() method is given below.

1. fileobj.read(<count>)
Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If the count is not specified,

then it may read the content of the file until the end.

Consider the following example.

Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");

#stores all the data of the file into the variable content
content = fileptr.read(9);

# prints the type of the data stored in the file


print(type(content))

#prints the content of the file


print(content)

#closes the opened file


fileptr.close()

Output:

<class 'str'>

Hi, I am

Read Lines of the file


Python facilitates us to read the file line by line by using a function readline(). The readline() method reads the lines of the file

from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file.

Consider the following example which contains a function readline() that reads the first line of our file "file.txt" containing

three lines.

Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");

#stores all the data of the file into the variable content
content = fileptr.readline();

# prints the type of the data stored in the file


print(type(content))

#prints the content of the file


print(content)

#closes the opened file


fileptr.close()

Output:

<class 'str'>

Hi, I am the file and being used as

Looping through the file


By looping through the lines of the file, we can read the whole file.

Example
#open the file.txt in read mode. causes an error if no such file exists.
fileptr = open("file.txt","r");

#running a for loop


for i in fileptr:
print(i) # i contains each line of the file

Output:

Hi, I am the file and being used as

an example to read a

file in python.

Writing the file


To write some text to a file, we need to open the file using the open method with one of the following access modes.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file exists.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
Consider the following example.

Example 1
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");

#appending the content to the file


fileptr.write("Python is the modern day language. It makes things so simple.")

#closing the opened file


fileptr.close();

Now, we can see that the content of the file is modified.

File.txt:

1. Hi, I am the file and being used as


2. an example to read a
3. file in python.
4. Python is the modern day language. It makes things so simple.
Example 2
#open the file.txt in write mode.
fileptr = open("file.txt","w");
#overwriting the content of the file
fileptr.write("Python is the modern day language. It makes things so simple.")
#closing the opened file
fileptr.close();

Now, we can check that all the previously written content of the file is overwritten with the new text we have passed.

File.txt:

1. Python is the modern day language. It makes things so simple.

Creating a new file


The new file can be created by using one of the following access modes with the function open().
x: it creates a new file with the specified name. It causes an error a file exists with the same name.

a: It creates a new file with the specified name if no such file exists. It appends the content to

the file if the file already exists with the specified name.

w: It creates a new file with the specified name if no such file exists. It overwrites the existing file.

Consider the following example.

Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x");

print(fileptr)
if fileptr:
print("File created successfully");

Using with statement with files


The with statement was introduced in python 2.5. The with statement is useful in the case of manipulating the files.
The with statement is used in the scenario where a pair of statements is to be executed with a block of code in
between.

The syntax to open a file using with statement is given below.

1. with open(<file name>, <access mode>) as <file-pointer>:


2. #statement suite

Consider the following example.

Example
with open("file.txt",'r') as f:
content = f.read();
print(content)

File Pointer positions


Python provides the tell() method which is used to print the byte number at which the file pointer exists. Consider
the following example.
Example
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())

File Pointer positions


Python provides the tell() method which is used to print the byte number at which the file pointer exists. Consider
the following example.

Example
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())

Renaming the file


The os module provides us the rename() method which is used to rename the specified file to a new name. The
syntax to use the rename() method is given below.

1. rename(?current-name?, ?new-name?)
Example
import os;

#rename file2.txt to file3.txt


os.rename("file2.txt","file3.txt")

Removing the file


The os module provides us the remove() method which is used to remove the specified file. The syntax to use the
remove() method is given below.

1. remove(?file-name?)
Example
import os;

#deleting the file named file3.txt


os.remove("file3.txt")

You might also like