Python Unit-4
Python Unit-4
File handling in Python is a powerful and versatile tool that can be used to
perform a wide range of operations.
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 so that the resources that are tied with the file are freed.
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening a File:
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode”
"t" - Text - Default value. Text mode
To open a file for reading it is enough to specify the name of the file:
f = open("demo.txt")
Because "r" for read and "t" for text are the default values, no need to specify them.
Note: Make sure the file exists, or else you will get an error.
Reading a File:
read(), readline(), readlines() are three important methods to read a file.
1) The open() function returns a file object, which has a read() method for reading
the content of the file.
f = open("demo.txt", "r")
print(f.read())
Output:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
If the file is located in a different location, you will have to specify the file path.
f = open("D:\\myfiles\demo.txt", "r")
print(f.read())
By default the read() method returns the whole text, but you can also specify how
many characters you want to return:
f = open("demo.txt", "r")
print(f.read(5))
Output: This
2) You can return one line by using the readline() method:
f = open("demo.txt", "r")
print(f.readline())
f = open("demo.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line.
f = open("demo.txt", "r")
for x in f:
print(x)
Output: This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
3) The readlines() method returns a list containing each line in the file as a list item.
Syntax:
file.readlines(hint)
Use the optional hint parameter to limit the number of lines returned. If the total
number of bytes returned exceeds the specified number, no more lines are returned.
f = open("demo.txt", "r")
print(f.readlines())
Output:
['This is line 1\n', 'This is line 2\n', 'This is line 3\n', 'This is line 4\n', 'This is line 5']
Write to an Existing File:
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file.
"w" - Write - will overwrite any existing content.
f = open("demo1.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demo1.txt", "r")
print(f.read())
Open the file "demo2.txt" and overwrite the content:
f = open("demo2.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the overwriting:
f = open("demo2.txt", "r")
print(f.read())
Create a New File:
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist.
"a" - Append - will create a file if the specified file does not exist.
"w" - Write - will create a file if the specified file does not exist.
f = open("myfile.txt", "x")
Closing a File:
It is a good practice to always close the file when you are done with it. Closing a file
will free up the resources that were tied with the file. It is done using
the close() method in Python.
f = open("demo.txt", "r")
print(f.readline())
f.close()
Manipulating file pointer using seek Programming
Syntax:
f.seek(offset, from_what), where f is file pointer
Parameters:
offset: Number of positions to move forward
from_what: It defines point of reference.
The reference point is selected by the from_what argument. It accepts three values:
Note: Reference point at current position / end of file cannot be set in text mode
except when offset is equal to 0.
Example 1: Let’s we have to read a file named “demo.txt”
f = open("demo.txt", "r")
# Second parameter is by default 0
# sets Reference point to twentieth index position from the beginning
f.seek(5)
# prints current position
print(f.tell())
print(f.readline())
f.close()
Output: 5
is line 1
Example 2: Seek() function with negative offset only works when file is opened in
binary mode.
f = open("demo.txt", "rb")
# Second parameter is by default 0
# sets Reference point to twentieth index position from the beginning
f.seek(-6, 2)
# prints current position
print(f.tell())
print(f.readline())
f.close()
Output: 72
b'line 5'