One of the must-know topics in programming is files. It is very useful, and you will have to use it in many situations. In this article, you will learn how to work with files in python through examples.
Let’s say you are writing a program and it has about 1000 lines of code. Now you want to stop coding and switch off the computer. Imagine if next time you switch on the computer you have to start writing the whole code again, so you can extend it further. It won’t be nice, will it be?
Another example, you finished creating the program that solves the problem we are addressing with this series of posts (read it again here). Now let’s say the company have 50 cars and 200 customers.
Does it mean every time the manager is going to use the software, he/she have to enter all the information about the cars and the customers to use the software you created?
No, definitely not. We have to use a mechanism that gives us the ability to store that data and read it anytime someone opens the application.
There are several solutions to this issue, the simplest one is to use files.
File basics
All the programming languages have support to work with files. You can also find libraries that give you the possibility of working with a complex type of files.
There are two types of files: plain text files (you must know them as txt files) and binary files.
Plain text files store the information as is typed. If you create a ‘txt’ file in your favourite plain text editor and open it in another text editor, you will see what you wrote.
On the other hand, binary files store the information codified. They do that for several reasons: to able to add format (text processors like Microsoft word or pages), to use less disk space, to hide the information from the reader if not using a specific application, etc.
You always have to follow these steps when working with files, independent the programming language you are using:
- Open the file
- Read/write from/to the file
- Close the file. In some programming languages, this is not necessary because the language do it implicitly.
- Use exception handling in all the three operations. If you missed the post of exception handling, you can read it here.
Files in python
Python, like every other programming language, has its own way of dealing with files. In this section, you will see the mechanisms provided by python to work with files.
To open a file in python you must use the function “open”. This function returns a file object that you will use later to read the data stored in the file.
This function has several parameters, Ill only explain the first two to make the post clearer. You can read an explanation of all the options here.
The first parameter is the name of the file and the second one is the mode that you want to use to open the file.
The mode can be open the file only for writing (w), only for reading (r, default option) or for adding (a) more information to the file. If you want to open the file for both reading and writing, then you can use ‘r+’ mode.
An example can be the following:
file = open(“myfile.txt”,”w”) # If the file does not exist, it will be created.
file = open(“myfile.txt”,”r”)
You can read from the file by using basically two methods. The first one reads the whole file at once. The second one read one line at a time.
file.read()
file.readline()
You can use the following code to iterate over the lines of a file.
for line in file:
#Your code here
To write to a file you just use the method write of the object (file.write(info)).
To close the file you can just use file.close().
Remember when working with files you have to do exception handling. Several errors can happen while working with files, for instance:
- You don’t have enough permission to open/write the file.
- The disk is full, and you are trying to save to the file.
- The file you are opening for reading does not exist.
A recommended way to work with files in python is to use the keyword ‘with’.
with open(“myfile”) as file:
#your code here
When you use this way, python ensures that the file is closed even if an exception occurs. So, you don’t have to do exception handling to make sure that the file is closed. Although you maybe have to catch the exception to print a user-friendly message.
Example of how to use files and python in a real-life project
Let’s apply this to our study case: The AutoCars company. If you don’t remember the problem description or you didn’t read it the post, you can read it here before you continue.
Now you have to save the information about all the cars into a file named “cars.txt”. The file will have one car per line.
The list of cars is stored in the class CompanyAutoCars (See it here). So, we have to implement the method in this class because is the one who owns the data we need to save to the file.
Save to file
def save_cars_to_file(self):
with open("cars.txt","w") as file:
for car in self._cars:
file.write(car.string_format())
def string_format(self):
return "%s,%s,%s,%s,%s,%s,%s\n" % \
(self._id, self._year_model, self._make, self._type, self._price_per_day, self._fuel, self._days_rented)
You can implement the method “string_format” in a different way.
Read from file
After reading from the file, we have to create the car objects and add them to the company.
def read_cars_from_file(self):
with open("cars.txt") as file: # r is the default mode
for line in file:
(id, model, make, type, price, fuel, days) = line.split(',')
car = Car(id, model, make, type, price, fuel)
self._cars.append(car)
As you can see above, we read each line of the file, create a car object with that info and then we add the car to the list of cars that the company have.
I created an extra method only for testing purposes. It will print all the cars in the company. I did it so I can check if after reading from the file the cars were added properly to the company.
def print_cars_info(self):
if len(self._cars)==0:
print ("There are no cars in the company")
return
for car in self._cars:
print (car.string_format())
Now let’s test the implementations using a console application.
if __name__ == '__main__':
# id, year_model, make, type, price_per_day, fuel)
car1 = Car(1, "2021", "BMW", "SUV", 300, "Petrol")
car2 = Car(2, "2021", "VW", "SUV", 200, "Petrol")
car3 = Car(3, "2021", "TOYOTA", "SUV", 200, "Petrol")
car4 = Car(4, "2021", "Nissan", "SUV", 200, "Petrol")
autocars = CompanyAutoCars()
autocars.add_car(car1)
autocars.add_car(car2)
autocars.add_car(car3)
autocars.add_car(car4)
autocars.save_cars_to_file()
autocars = CompanyAutoCars()
print("Cars currently in the company")
autocars.print_cars_info()
print("Cars currently in the company after reading from the file")
autocars.read_cars_from_file()
autocars.print_cars_info()
The result will be:
As you can see our code work fine.
You can add exception handling to the console app. So, in case there is a problem while reading or saving, you can give a proper message to the user.
Summary
File is an important topic in programming. We just saw how to work with files in Python, as well as some examples.
When working with files you must always follow this order:
- Open the file
- Read/Write from/to the file
- Close the file
- Always use exception handling. Some programming languages close the file always (as in python when you use the keyword “with”), but not all of. So, you have to be aware of whether or not the programming language does it implicitly.
Don’t forget to practice using real-life project examples.
Related posts:
- OOP in python: classes and objects
- Object-Oriented Programming: Python lists
- Software crash: exception handling in python
- How to check if a user input is an integer in Python?
H@appy coding!