In Python, a file is a data container that is used for permanent data storage. Files enable you to have your data stored even after program execution finishes.
A file can either be text or binary. Text files store the usual human-readable data. On the other hand, binary files store data in 1s and 0s.
When you open binary files, you’ll see a string of 1s and 0s, while when you open text files, you will see normal text (such as the one you are reading right now). Some examples of binary files are images and audio files.
In this guide, you will learn how to work with text files in Python.
How to Open Files in Python
To begin interacting with a file in Python, you need to associate the file on your disk with a file object in the program. This is known as opening a file.
To open a file in Python, developers use the open() function. This function takes in two string arguments: the file name and the mode. These two arguments must be put in quotes. You can use either double or single quotes, as in the following example code:
>>> file_object = open ("myfile.txt", "r") >>>
In case the file you are opening is not in the current directory, you can instead provide the file path and name of the file.
The mode in which you are opening the file defines what actions you are going to perform on the file object. There are three basic modes: r, w, and a.
- r: This mode opens the file for reading. If the file does not exist, then the compiler will give off an error.It is important to note that this is the default opening mode. Therefore, this will be the mode in which your file is opened in case you do not indicate any mode in the open() function.
- w: This mode opens a file for writing. It creates a new file if the file does not exist. If the file already exists, then it will overwrite all existing data within the file, so be cautious when using this mode.
- a: This mode opens a file for appending (adding) data to the end of the file. It creates a new file if the file does not exist.
- x: This mode opens the file for exclusive creation. If the file does not exist, it creates a new file. Unlike the w mode, if the file already exists, then the compiler will return an error.
The open() function also has some extended modes. These extended modes are simply a combination of the basic modes.
The table below summarizes them:
The file_object also has some attributes that can be used to get metadata about a file. These include:
- The name attribute returns the name of the file.
- The mode attribute returns the mode in which the file was opened.
- Then closed returns a boolean for whether the file is closed or not.
Here is how these different attributes look – and work – in Python code:
>>>file_object.name 'myfile' >>>file_object.mode 'r' >>>file_object.closed False
Reading and Writing to Files in Python
Before performing an operation on a file (reading or writing), you must have opened the file. In the previous section, you saw how to do that.
Writing to a File using Python
To write data to a file, you must have opened it in the w, a or x mode. You can use the write() method to write to a file. This method returns the number of characters (or bytes) that you have given to it. Here is an example of how to write to a file in Python:
>>>file_object.write("This is my first line.\n") 23 >>> file_object.write ( "This is so cool.") 16
Notice the special character \n in the first write() method. This is the default End of Line (EOL) character in Python. It creates a new line in the file. The next string argument will therefore begin from a new line.
Reading From a File in Python
To read (display) the contents of a file, you must have opened the file in the r mode or any of the extended modes.
You can use the read() method to read a file, as shown below:
>>>file_object.read() 'This is my first line.\nThis is so cool.\n'
If you do not indicate any argument in the read() method, then all the file contents will be read. The same happens if you indicate a negative integer.
You can specify how many characters should be read by indicating a positive integer argument:
>>> file_object.read(8) 'This is '
How to Close Files in Python
You always need to close your file after you have finished performing any operations on it. This ensures that all the changes you had previously made are successfully saved.
The following example code shows you how to use the close() method to close your files in Python:
It’s also worth noting that if the file object is assigned to another file, then the current file is automatically closed.
A safe way to ensure that your file always closes (even if you forget to explicitly do so) is by using the with clause. Any file opened within this clause will automatically close once program control shifts from this clause.
The syntax is:
with open (file_name, access_mode) as file_object: // open file here
Handling Files in Python
Unlike arrays and program variables, files ensure that the data processed during program execution is permanently stored.
Recall that it is important for you to always close your file after performing any operations on it. In fact, if you checked the contents of myfile.txt after writing your first line to it, you would have noticed that it was blank.
It’s only after you close the file, that you’ll see the changes you made. This goes to show how important it is for you to always close your file.