Opening, reading and writing to files is one of the most fundamental operations in programming. Fortunately, Python makes it quite easy to work with files. Unlike C or Java, the Python syntax for reading files is quite straightforward and the process itself easy to understand.

In this tutorial, we will learn how to open, read, and write to files in Python. We will also create a simple program that adds some content to an existing file and prints the output. To learn more about working with files in Python, check out this course on Python for beginners.

Reading Files in Python

Reading a file in Python involves not one, but two operations – opening and reading.

Before you can work with a file, you must first open it in Python using the open command. This is a bit like starting a car engine and holding the door open for the driver. As soon as you open a file, Python stores in the memory and preps it for further action.

After the file has been opened, you can use the read command perform an action on it, such as printing.

The syntax for these two commands is as follows:

Open:

                open(filename)

Read:

                filename.read()

This will become much clearer in the example below:

Example

In this example, we will create a simple text file, enter the file’s name as input and print it using the read command. Follow the steps below to get started:

Step 1: Fire up your text browser (Notepad, though I highly recommend Notepad++) and create a new text file. Enter any text you want. I chose this bit of Oscar Wilde witticism for my file:

“I am so clever that sometimes I don’t understand a single word of what I am saying.”

– Oscar Wilde

Save the file as sample.txt in the same folder as your main Python files.

Step 2: Create a new Python document. Since we want the user to provide the filename in the command line, we will use the sys.argv command line argument. If you remember your Python basics, you will recall that we can use it in our program with the from and import commands, like this;

                from sys import argv

Step 3: Recall that when we use argv, the first argument, argv[0] essentially stands for the script name (i.e. the name of the program itself). After that, we can pass as many arguments as we want.

Since we have one file to read, we will pass two arguments – the script name (argv[0]) and the filename, as shown below:

                script, filename = argv

Step 4: Now that we have the file name stored in the filename argument, we can open it using the open command:

                file = open(filename)

Step 5: Since we’ve already opened the file, we can print it using the read() command, like this:

                print file.read()

Thus, the whole program should look like this:

                from sys import argv
                script, filename = argv
                file = open(filename)
                print file.read()

Save the program with your preferred name. Make sure that you save it in the same directory as the text file.

Step 6: To run the program, open up command prompt and navigate to the directory where you’ve stored both your files. Run the program, passing the name of the file to be printed as an argument, like this:

step6

The results should be as follows:

result

That’s it! You’ve created your first program that uses Python’s read() command.

Confused by these commands? Master Python basics in this course on Python for rookies!

Prompting User for Filename

In the above example, we entered the filename in the command line ourselves with argv. But what if you wanted to prompt the user for the filename?

This is quite easy as well with the raw_input() command.

Enter the following code into a new Python program:

                print “Please enter the full name of the desired file (with extension) at the prompt below”
                #Raw_input is used to collect data from the user
                file = raw_input(“> “)
                #Opens the filename entered above
                file_open = open(file)
                print file_open.read()

Here’s the output:

output

Writing to a File

We’ve seen how easy it is to open and read a file, but what if you want to add some content to the file?

This is easy as well, thanks to the write() command. The syntax is quite straightforward:

open_filename.write(“Your content”)

As with the read() command, you first need to have the file open before you can write to it.

Let’s see how this command works in practice:

Example

In the program we created above, remove the print file_open.read() line and replace it with this:

                file_open.write(“This is an extra line”)

The program should look like this now:

                print “Please enter the full name of the desired file (with extension) at the prompt below”
                #Raw_input is used to collect data from the user
                file = raw_input(“> “)
                #Opens the filename entered above
                file_open = open(file)
                file_open.write(“This is an extra line”)

Go ahead and run it in the command prompt. This is what you should see:

example

Hmm…Python says that our file is not open for writing.

What does that mean exactly?

You see, Python has different modes when it opens a file. The default mode is set to read-only. If you want to write to a file, you will have to open a file in write-mode.

The proper syntax for doing so is as follows:

                open(filename, ‘mode’)

The modes are referred to by symbols like ‘r’, ‘a’, etc. Some of the most commonly used modes are:

r

Opens the file in read-only mode.

w

Opens the file in write mode. Deletes all existing content from the file.

w+

Same as above, except this command also creates a new file if the specified file doesn’t exist already.

a

Appends to an existing file

Since we want to add a line to our existing file, we will use the ‘a’ or append mode. This Stackoverflow thread has a great explanation of basic open modes.

Ready for some more challenge? Check out this intermediate course on Python to grapple more advanced topics!

Using Open Modes in Python

With the above knowledge, we can now rewrite our program as follows:

                file = raw_input("> ")
                file_open = open(file, 'a')
                file_open.write("This is an extra line")

Run the program again. If you check your sample.txt file, you should see the new line added at the end of the file:

sample.txt file

However, if you try to print the file using the read() command, you’ll see the following error:

read() command,

You’re getting this error because we’ve modified the file and haven’t opened it again. To solve this problem, we first need to close our open file. This can be done with the close() command, as shown below:

                file_open.close()

Tip: Closing a file after opening it is a good practice, regardless of whether you want to print it or not.

Since we’ve closed the file, we need to open it again. This time, we will pass the name of the file ourselves, like this:

                file_again = open("sample.txt")

Finally, we can print the modified file using the read() command:

                print file_again.read()

This is what our finished program looks like now:

file = raw_input("> ")
file_open = open(file, 'a')
file_open.write("This is an extra line")
file_open.close()
file_again = open("sample.txt")
print file_again.read()

And this is the output when we run it:

output2As you can see, the newly added line shows up at the end of our quote.

To recap, we learned four new Python commands – open(), read(), close() and write(). We also learned about open modes in Python and how to read and add content to a file. These four simple commands will be used a lot whenever you work with files, so make sure to practice them regularly.

For more in-depth knowledge of Python basics, try out this Python crash course for beginners.

Top courses in Python

Python and Django for Beginners
Navin Reddy
4.6 (8,799)
Learn Python & Ethical Hacking From Scratch
Zaid Sabih, z Security
4.7 (18,205)
The Python Bible™ | Everything You Need to Program in Python
Ziyad Yehia, Internet of Things Academy
4.6 (48,150)
REST APIs with Flask and Python in 2023
Jose Salvatierra, Teclado by Jose Salvatierra
4.6 (21,094)
Bestseller
Learn to Code with Python
Boris Paskhaver
4.7 (5,142)
Artificial Intelligence: Reinforcement Learning in Python
Lazy Programmer Team, Lazy Programmer Inc.
4.7 (9,753)
Bestseller
Python 3: Deep Dive (Part 1 - Functional)
Dr. Fred Baptiste
4.8 (10,315)
Python Network Programming for Network Engineers (Python 3)
David Bombal, Experts with David Bombal
4.7 (8,305)

More Python Courses

Python students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo