Files

Sometimes you want your program to get information from a file or to save some information in a file.

Wheather you want to read a file or write something in a file, it is important to remember that you always have to start by opening the file and end by closing it.

To open a file in Python, we will use the function open. This function takes as parameters:

  • the path to the file (with r in front of it if it’s an absolute path);
  • the opening mode.

The main different opening modes are:

  • ‘r’: opening as read only
  • ‘w’: opening in write mode. If the file exists, the content is deleted. If the file does not exist, it is created.
  • ‘a’: opening in append write mode. We write at the end of the file without deleting the previous content. If the file does not exist, it is created.

Once a file is open as read only, it is very easy to read its content using the read function.

If you opened the file in write mode, it is very easy to write something in it using the write function.

Warning

Don’t forget that if you want to add content, you should choose the “a” mode. The “w” mode will overwrite the content and you will start with an empty file.

Once you are done, all you have to do is close your file, using the close function.

Warning

Don’t forget to always close your file at the end of your program or this file will be locked, and other softwares won’t be able to use it.

Examples

🐍 Python Script
my_file = open(r"H\Python\file.txt", "w")
my_file.write("First time writing in a file using Python!")
my_file.close()
🐍 Python Script
my_file = open(r"H\Python\file.txt", "a")
my_file.write("Not the first time anymore...")
my_file.close()
🐍 Python Script
my_file = open(r"H\Python\file.txt", "r")
content = my_file.read()
print(content) # Will print the content of the file.
my_file.close()