Working with files is one of the most frequent operations that programmers have to perform, especially when there’s a lot of data-centric operations involved. Fiddling around with files such as text files, binary scripts, excel sheets, and so on, are some of the common use-cases. While there are advanced libraries to work with Excel sheets and CSV files that contain a huge amount of data, if you want to work with files that contain relatively lesser data, you can simply use one of the many built-in methods provided by Python to work with files. 

In this article, you will learn how to open a file in Python. But before you move on to explore these methods, you need to understand the different types of files that Python allows you to work with, and the modes that can be used to access them. So with no further ado, let’s get started.

Types of Files

Predominantly, Python allows you to work with the following two types of files. The first one is a plain and simple text file that you use on a day-to-day basis, and the second one is a binary file that is only machine-understandable, consisting of 0s and 1s.

  • Text files: Text file contains Unicode characters and has an extension of .txt. Each line in a text file is terminated by an EOL called End-of-line character, which is nothing but the newline (\n) character. This allows you to segregate specific lines.

  • Binary files: These are a combination of 0s and 1s. Unlike text files, there are no line terminators here. The Python interpreter first converts the 0s and 1s into a machine-understandable language and then stores the data accordingly.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Opening a File

As discussed earlier, you might want to work with files and manipulate them within a Python script. Suppose you want to use a particular set of data stored in a text file and you need to perform some operations on it or filter it. In such a case, it will require you to first open the file, make the required changes or simply access the data, and close it. This is exactly how you would do it using GUI file managers. And the same is the case with Python statements.

Python has an in-built method called open() which allows you to open files and create a file object. The general syntax of the open() method is -

FileObject = open(r"Name of the File", "Mode of Access and file type")

You don’t need to import a package or a library to use this method. There are two parameters that you need to provide along with the command. 

  • Name of the File

Here, you can either include only the file name or the entire path of the file. If you simply include the name of the file, you need to make sure that the Python script and the text file are inside the same directory. But, if you want to include the path of the file, you need to make sure that you include the character ‘r’ before the file path. This makes sure that the interpreter treats the file path as a raw string. For example, if the file path contains a directory called \temp, then the interpreter would throw an error because it would read \t as a special character called tab.

  • Mode of Access 

Here, you need to define what mode of access you want to give to the file and what type of file you want to open. Python allows you to read, write, and append to a file. The letters r, w, and a. denote these Along with that, you can provide the type of file. For a text file, you can include the letter ‘t’ and for a binary file, you can include the letter ‘b’. If you don’t provide the file type, by default, it understands that you have provided a text file. Hence, if you want to give write access to a binary file, the parameter will be “wb”.

Apart from that, there are different variations of each mode as well. Let’s discuss all of them.

Access Mode

Use

‘x’

It is used to create a new file that is empty.

‘r’

It is used to open the file in read-only mode. Moreover, the file must exist before you use this mode.

‘w’

It is used to open the file in write-only mode. If the file already exists, it is truncated to 0 characters or overwritten by the content that you provide. If it does not exist, then it gets created.

‘a’

It is also used to open the file in write-only mode. If the file already exists, it remains intact and the content is appended at the end. But if the file does not exist, it gets created.

‘r+’

It is used to open the file for both reading and writing, and the file should exist.

‘w+’

It is also used to open the file for both reading and writing. If it already exists, then it is either truncated or overwritten. If it does not exist, it gets created.

‘a+’

It is also used to open the file for both reading and writing. The only difference is if the file already exists, the content gets appended at the end. If not, then it gets created.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

In general, access modes determine the location of the filehandle as well. The filehandle is just like the cursor position in the file. Depending upon the access mode, the location of the filehandle is determined. For example, in the append mode, the file handle is at the end of the file. And in read mode, the filehandle is at the beginning of the file.

Next, consider the code below.

myfile1 = open("simplilearn.txt", "w")

myfile2 = open(r"/home/jarvis/Documents/simplilearn.txt", "r+")

Here, you have created two file objects for the same file. The first one is directly using the file name. This won’t throw an error because the text file and the Python script are in the same directory. The next one is by providing the file path. You need to use the r character in the beginning so that the interpreter reads the path as raw string.

Let’s use the open method with different access modes.

Let’s try to read the contents of a file into a file object and print it.

myfile1 = open("simplilearn.txt", "r")

print(myfile1.read())

myfile1.close()

Here, you have used the open method and provided the name of the file along with the read access mode. Next, you have invoked the read() method on the file object and printed its content. Then, you closed the file object to avoid wastage of memory and resources.

OpenFileInPython_1

You can write to a file using two different methods - write() and writelines(). The write() method simply writes a single string as a new line. The writelines method takes a list of strings and writes them into the file. Let’s see an example for both of them.

inputList = ["Hello and Welcome to Simplilearn \n", "We have tons of free and paid courses for you\n"]

inputString = "Hello and Welcome\n"

myfile1 = open("simplilearn.txt", "w")

myfile1.write(inputString)

myfile1.close()

print("Using the write method ...")

myfile1 = open("simplilearn.txt", "r")

print(myfile1.read())

myfile1.close()

myfile2 = open("simplilearn.txt", "w")

myfile2.writelines(inputList)

myfile2.close()

print("Using the writelines method ...")

myfile2 = open("simplilearn.txt", "r")

print(myfile2.read())

myfile2.close()

Here, you saw the creation of a list of strings and a simple string. First, you opened a file object in write mode and used the write method to write the simple string into the file, and then closed it using the close method on the file object. Then, you opened the file object in read mode and printed the contents that you just wrote using the write method, and closed the object again. You did the same for the writelines method next. Let’s check out the output of the program.

OpenFileInPython_2

To create a cleaner, intuitive, and efficient code, you can use the ‘with statement’. If you use a with statement, you don’t need to close the file object. It automatically takes care of the resource allotment and frees up space and resources once you move out of the with block. The general syntax is - 

with open <name_of_file> as  file

Let’s understand this with the help of an example.

inputList = ["Hello and Welcome to Simplilearn \n", "We have tons of free and paid courses for you\n"]

with open("simplilearn.txt", "w") as myfile:

   myfile.writelines(inputList) 

with open("simplilearn.txt", "r") as myfile:

   print(myfile.read())

Here, in the first with block, you opened a file in write mode and inserted a few sentences using the writelines method. In the next with block, you opened it in the read mode and printed the content. You don’t have to invoke a close method on the file objects as the with statements automatically takes care of it.

OpenFileInPython_3.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Wrapping Up!

To sum up, in this article you saw how to open a file in Python and why there would be a need to do so, in the first place. You skimmed through the different types of files, access modes, and how to open the file using the open() in-built method. You also saw how to use the read, write, and append modes, and in the end, you explored how to leverage the ‘with statement’ to create a more efficient and readable code.

If you are looking to master the python language and become an expert Python developer, Simplilearn’s Python Certification Course is ideal for you. Delivered by world-class instructors, this comprehensive certification course will not only cover the basics of Python, but give you in-depth expertise in key areas such as implementing conditional statements, handling data operations, Django, and shell scripting.

Have any questions for us on this How to open a file in Python article? If yes, leave them in the comments section of this article, and our experts will get back to you at the earliest!

Happy Learning!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449