Simple File Handling with Python

How to open, close, read, write, and append to files using Python

Ryan Ferdon
5 min readSep 13, 2022
Python logo next to a folder that contains files

In this article, we will take a look at some of the most common file handling operations in Python. We’ll learn how to open and close files, read and write files, and how to append data to an existing file. By the end of this post, you’ll have a solid foundation for working with files in Python!

Opening Files

The first step in working with files in Python is opening them up! This is done using the open() function.

The syntax for this function is as follows:

open(filename, mode)

The filename parameter represents the name of the file that you want to open. The mode parameter represents the mode in which you want to open the file. The most common modes are ‘r’ for read-only, ‘w’ for write-only, and ‘a’ for append.

Once you’ve opened a file, you can start reading or writing to it. But before we get into that, let’s take a look at an example:

f = open(“testfile.txt”, “r”) 

In the code above, we’ve opened up a new file called testfile.txt in write-only mode. Notice that we’ve assigned the resulting file object to the variable ‘f’. This is because once a file has been opened, it needs to be closed again afterward.

Note: You will have to declare the file path to the file you are trying to open if it is not in the current directory you are using Python in. Make sure to either duplicate all backslashes or prefix the path string with ‘r’. If you don’t, you will get a file read error.

"C:\\Users\\Ryan\\Desktop\\testfile.txt"  #double backslashes
r"C:\Users\Ryan\Desktop\testfile.txt" #'r' prefix

Closing Files

To close a file in Python we use the close() method. Closing files in Python is important for a few reasons.

  1. If you open a file in write-only mode, you cannot see the changes that you’ve made until you close the file.
  2. If a file is locked open in write-only mode, that file cannot be accessed outside of that program. This can cause other processes that use that file to fail.
  3. Having multiple files open at once can take up extra RAM and slow down your program.

Here’s an example of how to close a file in Python:

f = open(“testfile.txt”, “r”) #opens testfile in read-only mode
print(f.read()) #prints contents of testfile.txt to console
f.close() #closes the file

We opened the test file again in write-only mode. Only this time we closed the file when we were finished with it using the close() method.

Note: All text that follows a hashtag (#) on a line of code is a comment and not part of the code. Programmers use comments to clarify what that part of the code is intended to do. This helps with readability and troubleshooting the code.

Reading Files

Reading from files in Python is accomplished using the read() method. Here’s an example:

f = open(“testfile.txt”, “r”) 
print(f.read()) #prints contents of testfile.txt to console
f.close() #closes the file

In this code snippet, we’ve opened up our test file again, but this time in read-only mode (‘r’). We then use the read() method on our file object (represented by f) to print out the contents of our file to the console.

Pretty simple so far! But what if we only want to read part of a file? In that case, we can use one of two methods: readline() or readlines().

Let’s take a quick look at each one:

readline(): reads a single line from a file and returns it as a string object

readlines(): reads all lines from a file and returns them as a list of string objects

Here’s an example of how each one works:

f = open(“testfile.txt”, “r”) 
print(f.readline()) #prints first line of testfile
print(f.readlines()) #prints entire contents of testfile as list
f.close() #closes the file

As you can see from the example above, using readline() will print out just the first line of our text file (since it only reads one line at a time). On the other hand, using readlines() will print out all lines from our text file (since it returns them as a list).

Writing Files

Now let’s move on and talk about writing data to files… To write data to files using Python, you need to make use of either writelines() or write(). These two methods are pretty similar: writelines() writes multiple lines at once while write() writes just one line at once.

f = open(“testfile.txt”, “w”)
list = ["Roses are red \n","Violets are blue \n"]
f.write("--Coding Poem-- \n") #writes single line
f.writelines(list) #writes multiple lines
f.close() #closes the file

Caution: Opening a file in write-only mode will overwrite any data that is already on that file.

Appending To Existing Files

Another common operation when working with files is appending data i.e., adding data onto an already existing file without overwriting anything else.

f = open(“testfile.txt”,"a")
list2 = ["I learned how to code \n","And so can you!"]
f.writelines(list2)
f.close() #closes the file

In the above code snippet, we opened the testfile3 file in append mode. We then appended a line of text to the file and closed the file.

If you followed along with the writing files and appending to existing files sections, you should have a text file with a poem that looks like this:

four-line coding poem

You can also practice with the read() modules using this file.

Conclusion

So there you have it! A crash course on some common operations when working with files Python. With these simple operations, you can do a lot of different things. Now go forth and start building amazing things!

If you enjoyed this article, please follow me to read my future articles.

Also, feel free to check out my blog.

--

--

Ryan Ferdon

I’m a programmer, leader, and entrepreneur. I’m excited about new technology, automation, entrepreneurship, cryptocurrency, and data.