Opening a text file
To open a text file in Python, we use the built-in function open() . The open() function takes two arguments: the name of the file and the mode of opening. The name of the file can be a relative or absolute path , and the mode of opening can be one of the following:
Mode |
Description |
“r” |
Open a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. |
“r+” |
Open a file for both reading and writing. The file pointer is placed at the beginning of the file. |
“w” |
Open a file for writing only. Overwrites the file if it exists. Creates a new file if it does not exist. |
“w+” |
Open a file for both writing and reading. Overwrites the existing file if it exists. Creates a new file if it does not exist. |
“a” |
Open a file for appending. The file pointer is at the end of the file if it exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. |
“a+” |
Open a file for both appending and reading. The file pointer is at the end of the file if it exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. |
The syntax of open() is as follows:
file_object= open(file_name, access_mode)
This function returns a file object called file handle which is stored in the variable file_object . We can use this variable to transfer data to and from the file (read and write) by calling the functions defined in the Python’s io module . If the file does not exist, the above statement creates a new empty file and assigns it the name we specify in the statement.
For example, to open a file named “Book.txt” in read mode, we can write:
f = open("Book.txt", "r")
Closing a text file
To close a text file in Python, we use the close() method of the file object. The close() method releases the resources associated with the file and ensures that any changes made to the file are saved. It is important to close a file after using it to avoid errors or data loss.
The syntax of close() is:
file_object.close()
Here, file_object is the object that was returned while opening the file.
For example, to close the file object f, we can write:
f.close()
Opening a file using with clause
Another way to open and close a text file in Python is to use the with clause. The with clause creates a context manager that automatically closes the file when the block of code under it is finished. This way, we don’t have to worry about closing the file manually or handling any exceptions that may occur while working with the file.
The syntax of with clause is:
with open (file_name, access_mode) as file_ object:
For example, to open a file named “Book.txt” in read mode using the with clause, we can write:
with open("Book.txt", "r") as f:
# do something with f
Writing to a text file
For writing to a file, we first need to open it in write or append mode .
- If we open an existing file in write mode , the previous data will be erased , and the file object will be positioned at the beginning of the file.
- On the other hand, in append mode , new data will be added at the end of the previous data as the file object is at the end of the file.
After opening the file, we can use the following methods to write data in the file.
- write() - for writing a single string
- writelines() - for writing a sequence of strings
The write() method takes a string as an argument and writes it to the file.
The writelines() method takes a list of strings as an argument and writes them to the file as separate lines.
For example, to write some data to a file named “Book.txt” in write mode, we can write:
with open("Book.txt", "w") as f:
f.write("This is a book.\n")
f.write("It has many pages.\n")
f.writelines(["It is written by an author.\n", "It is published by a publisher.\n"]
Reading from a text file
We can write a program to read the contents of a file. Before reading a file, we must make sure that the file is opened in “r”, “r+”, “w+” or “a+” mode. There are three ways to read the contents of a file:
The read( ) method
This method is used to read a specified number of bytes of data from a data file .
The syntax of read() method is:
file_object.read(n)
If no argument or a negative number is specified in read(), the entire file content is read.
The readline(n) method
This method reads one complete line from a file where each line terminates with a newline (\n) character. It can also be used to read a specified number (n) of bytes of data from a file but maximum up to the newline character (\n).
The syntax of readline() method is:
file_object.readline(n)
If no argument or a negative number is specified, it reads a complete line and returns string.
To read the entire file line by line using the readline() , we can use a loop . This process is known as looping/ iterating over a file object . It returns an empty string when EOF is reached
The readlines( ) method
The method reads all the lines and returns the lines along with newline as a list of strings.
When we read a file using readlines() function, lines in the file become members of a list, where each list element ends with a newline character (‘\n’).
The syntax of readlines( ) method is:
file_object.readlines()
Seek and tell methods
To get or set the position of the file pointer in a text file in Python, we use the tell() or seek() methods of the file object.
Seek method
This method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
In the above syntax,
- offset is the number of bytes by which the file object is to be moved.
- reference_point indicates the starting position of the file object. That is, with reference to which position, the offset has to be counted. It can have any of the following values:
- 0 - beginning of the file
- 1 - current position of the file
- 2 - end of file
Tell method
This function returns an integer that specifies the current position of the file object in the file. The position specified is the byte position from the beginning of the file till the current position of the file object.
The syntax of using tell() is:
file_object.tell()
Creating and Traversing a text file
To create a text file in Python , we use the open() function with the “w” or “a” mode . The “w” mode creates a new file or overwrites an existing file, while the “a” mode creates a new file or appends to an existing file.
For example, to create a text file named “practice.txt” in write mode, we can write:
f = open("practice.txt", "w")
To traverse a text file in Python , we use a loop to iterate over the lines or characters in the file. We can use the readlines() method to get a list of all the lines in the file, or the read() method to get the entire content of the file as a single string.
For example, to traverse a text file named “practice.txt” in read mode, we can write:
f = open("practice.txt", "r")
lines = f.readlines() # get a list of lines
for line in lines: # iterate over each line
print(line) # print the line
f.close() # close the file
OR
f = open("practice.txt", "r")
data = f.read() # get the whole content as a string
for char in data: # iterate over each character
print(char) # print the character
f.close() # close the file