Python File methods (With Useful Examples)

If you are a beginner and want to learn about Python file methods, this tutorial will explain them.

Whenever I work on a Python project, I must interact with files on my system. I use the Python file methods to perform certain operations on the file, such as reading, writing, truncating, etc.

In this tutorial, I have explained the most commonly used Python file methods in detail for the beginner level; if you don’t know about file methods in Python, don’t worry. This tutorial covers file methods, like how they work and how to use them.

Let’s begin

Python File Methods

Python has different file methods for working with files on your system, such as reading, writing, opening, etc. These methods allow you to perform a wide range of operations on files.

Below is the list of the file methods in Python.

  • Python file method open()
    • Python file method read()
    • Python file method write()
      • Python file method writelines()
    • Python file method readline()
    • Python file method seek()
      • Python file method tell()
    • Python file method flush()
  • Python file method close()

I will explain each of the above Python file methods one by one.

Open() File Methods in Python

The open() file method is used to open the file in a specific mode, such as you can open the file in reading (r), writing (w) and appending (a) mode.

Before performing any operation on a file, you must open it in one of the three modes (r, w, a), depending on what you want to do with it.

The syntax is given below.

file = open("filename", 'mode')

Where,

  • open(): This is the file method used to open the file; it accepts two parameters: filename and mode.
  • filename: This is the file name you want to open, including the complete path to the file on your system.
  • mode: Mode means whether you want to open a file for reading or writing or appending something to it. So you can specify three modes, ‘r’ for reading, ‘w’ for writing and ‘a’ for appending.

Remember, when you open a file in any of the three modes using the open() function, a file object is created; you can use this file object to call another file method for specific operations.

For example, the computer has a file called data.txt. You can use the open() method to open this file, as shown in the code below.

file = open("/content/data.txt",'r')
print(file)

When you execute the above code, it takes your file data.txt at the specified path and opens it in the reading mode because here mode is ‘r’, and returns the file object you can see in the picture below.

Open() File Methods in Python

When you print the file object, it shows ‘<_io.TextIOWrapper name=’/content/data.txt’ mode=’r’ encoding=’UTF-8′>’ means the file is opened in reading mode.

Now that you have opened the file in reading mode, you might want to read its content. For that, you can use the read() method. Look at the next section.

Read() File Methods in Python

The read() method allows you to read the content of the opened file. Call this method on the file object to read the file’s content.

The syntax is given below.

file_object.read(bytes_to_read)

Where,

  • file_object: The file object returned by the open() function.
  • read(bytes_to_read): The read() function reads the file’s content and accepts an option argument called bytes_to_read, which means several bytes to read from the file. If this argument is not provided, it reads the entire file content by default.

For example, I will open the same file, data.txt, using the open() method.

file = open("/content/data.txt",'r')

The above code opened the file in read mode and returned the file object, which can be referenced by the name ‘file’.

To read the file’s content, call the read() method on the file object, as shown in the code below.

print(file.read())
Read() File Methods in Python

Look when calling the file.read() method on the file object. It returns the file’s content, which is ‘You are learning Python file methods.’

Right now, the file data.txt contains one sentence line, so it returns the entire sentence. Suppose you want to read only the 10 bytes of the file. you can specify this within the read() function, as shown in the code below.

print(file.read(10))
Read in Bytes using the Read() File Methods in Python

Look at the output. Specifying 10 bytes in the read() method returns the character from the file, which is ‘You are le’.

Now, if you are again, call the read() function with 5 bytes; then, it reads content from the last read bytes but doesn’t read the content from the beginning.

This is how to use the read() file method in Python.

After reading the file, you may need to write something to the file; for that, you can use the write() method; check the next section.

Write() File Built-in Methods in Python

The write() method of Python writes text (or bytes) to a text file. To use this method, call it on the file object with the string or data you want to write.

The syntax is given below.

file_object.write(bytes_to_write)

Where,

  • file_object: The file object returned by the open() function.
  • write(bytes_to_write): The write() function writes the content to the file and accepts an option argument called bytes_to_write, which means bytes to write to the file.

For example, suppose you must write the daily task to the file task.txt on your computer. First, open the file in appending mode using the code below.

file = open("/content/task.txt",'a')

Remember, if the file doesn’t exist at a specified path, it creates a new file of that name (task.txt) and returns the file object. The ‘task.txt’ on my computer doesn’t exist at path ‘/content/’, so the above creates a new file.

READ:  How to convert string to boolean in Python? [6 Methods]

After opening the file in append mode (‘a’), call the write() method on it with the string (bytes) that you want to write to it. Look and execute the code below for that.

file.write("Get up at 4 A.M ")

The string ‘Get up at 4 A.M ‘ is written to the file task.txt using the above code. When you execute the above code, it returns an integer number denoting the number of bytes written to the file.

After this, your data is not written to the file yet; it is in something called a buffer, which means that after calling the write() method on the file object, your data or string will not appear in your file.

To appear the data or string you wrote to it, you must close the file object by calling the close() method, as shown in the code below.

file.close()
Write() File Built-in Methods in Python

After executing the above code, your data becomes visible within the file ‘task.txt’.

Let’s read the file. To do so, open the ‘task.txt’ file in read mode and call the read() method to read its entire content, as shown in the code below.

file = open("/content/task.txt",'r')
file.read()

Permanently close the opened file when you no longer need to perform any operation on the file.

file.close()
View the File Content After Performing the Write Operation

Look at the output; it is the exact string you wrote using the write() method. This is how you can use the write() method on the file object to write bytes of data to the file.

However, in Python, write() is not the only method to write the content in a file; there is one more variant of this method called writelines(). Check it in the next section.

Writelines() File Method in Python

Python’s writelines() method writes multiple lines of string to the file in one go. The writelines() can write the sequence or list of strings to the file. It can also write a single string.

The syntax is given below.

The syntax is given below.

file_object.writelines(list_of_strings)

Where,

  • file_object: The file object returned by the open() function.
  • writelines(list_of_strings): The writelines() function writes the sequence of strings to the file and accepts an option argument called list_of_strings, which has multiple lines of string to write to the file: it can be an iterable object like a tuple or list.

For example, suppose you have a list of strings, as shown below.

tasks = ["Go for walk\n", "Do the breakfast\n", "Get ready for the office\n"]

As you can see, the list ‘tasks’ contains multiple tasks as strings. To write each string to a file at once, use the writelines() function by following the below steps:

Open the same file ‘task.txt’ in the append by specifying the ‘a’ as a mode in the open() method, as shown in the code below.

file = open("/content/task.txt", "a")

After opening the file, call the writelines() method with the list of tasks you want to write to it, as shown in the code below.

file.writelines(tasks)

After this, the file is closed using the code below.

file.close()
Writelines() File Method in Python

To see the file content, I want to introduce you to a new Python file method called readlines(). Look at the next section for this.

Readlines() File Method

The readlines() method is similar to the read() method, but it returns each line of the file as a list of lines. Suppose you have a text file containing four lines of string; this method returns the list of lines, each representing the string of the file.

The syntax is given below.

file_object.readlines(bytes_to_read)

Where,

  • file_object: The file object returned by the open() function.
  • readlines(bytes_to_read): The readlines() function reads the file’s content line by line, returns the list of lines, and accepts an option argument called bytes_to_read, which means several bytes to read from the file. If this argument is not provided, it reads the entire file content by default.

For example, read the file ‘task.txt’ you created in the preceding section. Open the file in the read mode using the code below.

file = open("/content/task.txt", "r")

Now, call the readlines() method on the file, as shown in the code below.

file.readlines()

Now close the file.

file.close()
Readlines() File Method

Look at the output; the readlines() method returns the file content as a list of strings or lines like ‘[‘Go for walk\n’, ‘Do the breakfast\n’, ‘Get ready for the office\n’]’.

Also, look at each string in the list containing the ‘\n’ at the end, which is the next line character.

This is how to use the readlines() method for a Python file.

Seek() File Methods in Python

Before learning about the seek() method, you must know, ‘What is the file pointer in the file?’.

You opened the file to read and write or to perform input/output operations. But have you ever wondered how Python file methods know where to write and read from the file?

I mean, how is it decided that methods like read(), write(), etc., will start writing to or reading the file from a specific location, and how is this location determined? this is where the concept of file pointer comes in.

The file pointer is an indicator or reference point used to specify the current position within a file. In other words, it keeps track of the location within the file from which the next read or write operation will be performed.

READ:  Print quotes in Python [6 methods]

So, when you open the file using the open() method in the read or write mode, a read or write file pointer is associated with that file; this file pointer points to the beginning of the file in general, which means the next read or write operation will be performed from the beginning of the file.

So, when data, such as a string, is written or read from the file, the file pointer is automatically updated to reflect its current position within the file.

Now you understand what file pointers are, suppose you want to change the position or location of this file pointer within the file to a different position or location; how will you do that? this is where the Python seek() method can help you.

The seek() method allows you to set the file pointer position or the current position of the file pointer to a different position within the file from which the next read or write operation will be done.

The syntax is given below.

file_object.seek(offset, whence)

Where,

  • file_object: The file object returned by the open() function.
  • offset: It represents the number of bytes to move the file pointer within the file. When you specify the offset in negative, it moves the file pointer backwards, but for positive offset, it moves the file pointer forward.
  • whence: It determines from where the file pointer should move or in which direction, like forward and backwards. The following three values can determine it:
    • When ‘whence’ is set to 0, it means moving the file pointer to a specified number of bytes from the beginning of the file.
    • When ‘whence’ is set to 1, it means moving the file pointer to a specified number of bytes from the current position of the file pointer within the file.
    • When ‘whence’ is set to 2, it means moving the file pointer to a specified number of bytes from the end of the file.

But before we move into the practical example of the seek() method, I want you to introduce one more method: tell(). This method returns the current position of the file pointer within the file.

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

file_object.tell()

Call the tell () method on the file object to find out the position of the file pointer within the file.

So, from now on, use the seek() method to set the current position of the file pointer within the file and the tell() method to know the current position of the file pointer within the file.

For example, open the file named ‘data.txt’ in the write mode using the open() method, as shown in the code below.

file = open("/content/data.txt", "w")

The above code creates and opens an empty file at the path ‘/content/’ in your director.

Let’s check the position of the write file pointer within the newly created file ‘data.txt’ using the tell() method, as shown in the code below.

file.tell()
Tell() File Method in Python

Look at the output; the tell() method returns the current position of the write file pointer as 0, which means the write pointer is pointing to the beginning because the file is empty.

Let’s write some content to it using the write() method, as shown in the code below.

file.write("Python")

When you execute the above code, it writes the word ‘Python’ to the file ‘data.txt’; as you can see, the word consists of 6 characters and each character is represented by one byte of space.

So, the current position of the write file pointer within the file should be at the 6th byte. Let’s check that by calling the tell() method on the file object again, as shown in the code below.

file.tell()
Checking the Current Position Using the Tell() File Method in Python

Look at the output. This time, the tell() method returns the current position of the write file pointer as 6.

Now, move the current position of the write file pointer 20 bytes forward from the beginning of the file using the seek() method, as shown in the code below.

file.seek(20)

Check the current position using the tell() method, as shown in the code below.

file.tell()
Seek() File Methods in Python

Look at the output. The seek(20) method moves the write file pointer to the 20th byte or index position from the beginning of the file. To verify that, the tell() method returns the current position of the write file pointer as 20.

But remember, when you open the file in the ‘r’, ‘w’ and ‘a’ modes, the whence parameter values 1 and 2 don’t work; only the value 0 works. For example, moving the file pointer to 20 bytes backwards from the current position using the code below shows an error.

file.seek(-20, 1)
Using the Whence Parameter of Seek() File Methods in Python

The above code returns an error when the whence value is set to 1 within the seek(-20, 1) method.

But when you open the binary file using the modes ‘rb’, ‘wb’, and ‘ab’, the whence parameters 1 and 2 work.

For example, open the new binary file named ‘binary.txt’ in the appending mode by specifying the mode as ‘ab’, which stands for ‘append binary’.

file = open("/content/binary.txt", "ab")

After opening the binary file in the append mode, write some bytes using the write() method, as shown in the code below.

file.write(b"This is the binary data")

Here, within the write() method, the binary data is specified, which is b”This is the binary data.” this string is prefixed with the letter ‘b’, meaning the whole string is bytes literal.

READ:  Python remove Non ASCII characters from String [7 Methods]

After writing the bytes data to the ‘binary.txt’ file, check the current position of the file pointer using the tell() method.

file.tell()
Using the Whence Parameter of tell() File Methods in Python with Binary File

Look at the output. After writing the binary data to the file, the current position of the file pointer within the file is 23, as you can see in the output.

Now, if you want to move the current position of the file pointer to 10 bytes in the forward direction, use the seek() method and pass the offset as 10, with a parameter value of 1.

file.seek(10, 1)

After moving the file pointer’s position, check its current position in the file using the tell() method.

file.tell();
Using the Whence Parameter of Seek() File Methods in Python with Binary File

As you can see in the output, the file pointer moved 10 bytes forward from its current position, so the tell() method returns its new position as 33.

Because the file pointer’s previous position was 23, moving it 10 bytes in the forward direction makes it 33.

You can also move the file pointer position backwards by specifying the negative offset value. For example, move the file pointer position to 20 bytes in the backward direction from the current position. For that, look and execute the code below.

file.seek(-20, 1)
file.tell()
Moving File Pointer in Back Direction Using Seek() File Methods in Python with Binary File

Look at the output. By specifying the negative offset value as -20, the file pointer moved 20 bytes backwards from its current position; as a result, the tell() method returns the file pointer’s current position as 13.

Now you know how to use the seek() method to change the position of the file pointer within the file in both directions, forward and backward.

Finally, let’s set the ‘whence’ parameter of the seek() method to 2 to move the file pointer to the end of the file from its current position.

file.seek(0,2)

Check the current position.

file.tell()

When you execute the code above, it shows the current position of the file pointer as 23. If you remember, this was the position when you first performed the write operation on the file.

Now close the file after working with it.

file.close()

Next, let’s learn about the flush() method of Python files.

Flush() File Method in Python

First, let me develop your concept for the flush() method. Whenever you open a file and perform a write operation, the data is not written directly to the file. Instead, it is written or stored in an internal buffer.

If you remember from the section where you learned how to use the write() method, I showed one example where you have written data to the file using the write() method, but when you try to read that data using the read() method before closing the file, you don’t see anything in the file.

So, you don’t see becasue your data is written to the buffer, there are two ways to take the data from the buffer to the file.

The first is to call the close() method on the file to take the data from the buffer to the file automatically, and the second is to call the flush() method to take the data from the buffer to the file without closing the file.

Whenever the buffer gets full, it automatically writes the data to the file. This process is called flushing. So, you use the flush() method to flush the data from the buffer.

For example, open the new file named ‘data.txt’ in the appending mode using the code below.

file = open("/content/data.txt", "a")

Use the write() method to write data to the file’s ‘data.txt’ as shown in the code below.

file.write("This is the classified data")

The above code writes the data to the file, but your data is in the internal buffer; it is not written to the file yet. To verify that, open the file named ‘data.txt’ at the specified path.

Viewing the File Before Using the Flush() File Method in Python

Look at the picture. I opened the file ‘data.txt’, but this file doesn’t contain any written data. So, data is stored in the internal buffer. To flush this buffer, you must call the flush() method, as shown in the code below.

file.flush()
Flush() File Method in Python

After executing the flush() method on the file object, data is written from the buffer to the file, so you can see in the picture that the file name ‘data.txt’ contains the written data.

You can use the flush() method to write the data from the buffer to the file immediately.

Well, you have been learning about several file methods, like read(), write (), seek(), etc., but one method you need to execute whenever you open the file is close(). Check the next section.

Close() File Methods in Python

Python’s close() file method closes the opened file in any mode. So, the file is opened to perform a specific operation on it; when the operation is done, the file must be close to realise the number of system resources used by this file.

The syntax is given below to close the file.

file_object.close()

You must call the close() method on the file object to close that file.

After closing the file, the file object cannot be used to perform operations on it; if you try to perform any operation, such as reading or writing, it raises an error.

I hope you understand Python file methods and how to use them for different operations.

Conclusion

In this Python tutorial, you learned about Python file methods such as open(), read(), write(), writelines(), readlines(), seek(), tell(), flush() and close().

While learning about those methods, you also knew the file pointer and buffer concept.

You may like to read: