Opening a File Using open() Method in Python

Opening File With Open() In Python

Introduction

We have come across the various operations that could be performed on a file using Python, like reading, writing, or copying. In performing any of these mentioned file- handling operations, it was clear that opening the file is the first step.

So today in this tutorial, we are going to focus on the file opening part using the Python open() method.

The open() Method in Python

The open() method opens a particular file in the specified mode and returns a file object. This file object can be then further be used for performing various file manipulations. The syntax for using the method is given below.

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Here,

  • file refers to the file name/descriptor and mode is the mode in which the file is to be opened. These are the basic parameters required for opening a file.
  • buffering is an optional integer used to set the buffering policy. By default it is set to (-1),
  • encoding is the name of the encoding used to decode or encode the file,
  • errors is an optional string that specifies how encoding and decoding errors are to be handle. Note, this cannot be used in binary mode.
  • newline controls how universal newlines mode works (it only applies to text mode). It can be None(default), '', '\n', '\r'and '\r\n'.
  • closefd denotes whether the passed file parameter is a file name or a file descriptor. It should be False when a file descriptor is mentioned. Or else True(default). Otherwise, an error will be raised,
  • opener is a callable custom opener. The specified file descriptor for the file object is obtained by calling this opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).

Opening modes for open() in Python

The different file opening modes with there meaning are given below.

ModesDescription
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)
Table for file opening modes

Python open() Example

Now that we are done with the basics of the open() method in Python, let us jump right into some examples.

We are going to open a file named file.txt with contents(as shown below) using the open() method.

File Contents
File Contents

Look at the code snippet give below carefully.

# opening a file
f = open('file.txt', 'r')  # file object

print("Type of f: ", type(f))

print("File contents:")

for i in f:
    print(i)

f.close()  # closing file after successful operation

Output:

Type of f:  <class '_io.TextIOWrapper'>
File contents:
Python

Java

Go

C

C++

Kotlin

Here, we have opened the file file.txt in read-only(' r ') mode. The open() method returns a file object to f . Then we have iterated through this object using the for loop to access the content of the file.

After that, we have closed the file using the close() method. It is important to close a file at the end after performing any operations over it to avoid errors. These errors could occur while opening the same file again.

Opening Multiple Files

In Python, we can open two or more files simultaneously by combining the with statement, open() method, and comma(' , ') operator. Let us take an example to get a better understanding.

Here, we have tried to open two independent files file1.txt and file2.txt and print their corresponding content.

# opening multiple files
try:
    with open('file1.txt', 'r+') as a, open('file2.txt', 'r+') as b:
        print("File 1:")
        for i in a:
            print(i)
        print("File 2:")
        for j in b:
            print(j)
except IOError as e:
    print(f"An Error occured: {e}")

# file closing is not required

Output:

File 1:
John Alex Leo Mary Jim
File 2:
Sil Rantoff Pard Kim Parsons

Note: We have not closed the files after using this time. It is because we do not need to, the with statement ensures that the opened files are closed automatically by calling the close() method.

Conclusion

So that’s it for today. Hope you had a clear understanding. For any further related questions feel free to use the comments below.

We recommend going through the links mentioned in the references section for more info.

References