Recommended Books

Python File Handling



File handling is an integral part of any programming language. Why learn Python File Handling?

  1. File handling gives you the ability to store data permanently. (Saving data after a program terminates)
  2. File handling gives you the ability to load data from files to use in your program. (Loading save files to re continue previous task)
  3. Creating a “log” file to record all events occurring during execution of software.

Opening files

The open function is used establish a connection between your program and the target file. If this command is executed successfully, you can proceed to write, read or append data from the file.

Keep in mind that the open command does not trigger a code block like if else, while and for loops do. There is no need for indentation. There may be any number of lines and code blocks between the open and close statements.

file = open("Sample.txt")

Closing files

Once you’re done working with the file, you should always remember to close the connection the close function. While your program will not throw in error if you don’t, it’s considered good practice.

file.close()

Reading from Files

With the read function, you can “read” all the data contained within a file. Remember to open the file first in read mode. You can do this by adding a “r” as a parameter in the open function.

Note: read is actually the default open mode, but it’s good practice.

There are several ways to read data from a text file, each of them returning the data in a unique way. The most common is the .read() function, which reads all the data in one go.

file = open("Sample.txt")
print(file.read())
file.close()
# Output
Hello World
This is a file with sample text
Spam and eggs

Note that the data was displayed exactly how it was written in the file. The read function accounts for different lines.

The read function takes one parameter, “Number of characters”. Say that you’re importing data from a really large file, and only want the starting part of it. You can specify the exact number of the characters you wish to be displayed.

file = open("Sample.txt")
print(file.read(11))
file.close()
# Output
Hello World

Another in-built function for reading data is the readline() function. Unlike the read function which reads all the data, the readline() function reads just one line.

file = open("Sample.txt")
print(file.readline())
file.close()
# Output
Hello World

Another way of reading data is iterating over it with a for loop. This method does not involve the read function.

file = open("Sample.txt")
for x in file:
    print(x)
file.close()
Hello World

This is a file with sample text

Spam and eggs

If you’re wondering why there is a line gap between each line, that’s not a mistake. This is actually an obstacle that you’ll face during file handling. See the Advanced File handling page for more. (The problem is actually caused by python reading a newline statement).

Things to remember while reading data:

  1. Make sure the file actually exists, else an error will be thrown.
  2. Remember to write the full name of the file, including it’s extension
  3. If the file is not in the same directory as the python script, you’ll have to include the full path. e.g: “C:/Users/Coder/Files/Sample.txt”

Writing to Files

The write function allows you to write data to a file in python. To open a file in write mode, add “w’ as a parameter to the open function.

file = open("Sample.txt", "w")

Things to remember while writing to files:

  1. If the file does not exist, a new file will be created with the given name.
  2. If the file does exist, it will be overwritten with a blank file of the same name. Any previous data will be over-written.
  3. Remember to write the full name of the file, including it’s extension.
  4. If the file is not in the same directory as the python script, you’ll have to include the full path. e.g: “C:/Users/Coder/Files/Sample.txt”.
file = open("Sample.txt", "w")
file.write("Sample data to be written")
file.close()

You can also place a variable within the parameters of the write function.

file = open("Sample.txt", "w")
var = "Sample data to be written"
file.write(var)
file.close()

There is another parameter you can use in place of “r”, that is exactly the same, but will not overwrite the file if it already exists. The “x” parameter.

Append to File

The append function can be used to add data into a file. Due to the nature of text files however, (They store data sequentially) new data can only be added to the bottom of the file. It’s parameter is “a”.

The append function will create a new file if the file does not already exist.

file = open("Sample.txt", "a")
file.append("Appending Data")
file.close()

Extra Examples:

This is a technique that can be used to get all lines in a file, one by one. Since an empty line is the equivalent to ” “, we set the condition on the while loop to end when the var variable is equal to ” ” (also known as null).

file = open("Sample.txt")
var = "empty"
while var != "":   
    var = file.readline()
    print(var)  
file.close()
Hello World
This is a file with sample text
Spam and eggs

Keep in mind that these were the very basics of Python File handling. File Handling in Python is a really large subject, with many complexities. If you want to learn more, head over to the Advanced File Handling Page, where you will learn how to edit files, read and write in unique scenarios, parse data and more.


This marks the end of our Python File Handling Guide. If you have any suggestions or contributions to make, feel free to do so. Anything to help improve our site, CodersLegacy is welcome.