File Handling in Python
Hello everyone! I am one of Sisterslab’s Women in Tech Academy project participants, supported by Toplum Gönüllüleri Vakfı. The project aims to empower 25 women between the ages of 20–28 with software training for 3 months and seek their participation in the workforce in the sector. You can find more information about the project at this link: https://sisterslab.co/women-in-tech-academy/
In today’s medium post, I will cover basic file operations in python. After this article, you will be able to open a file and do basic operations like reading and writing in that file.
Photo by Avel Chuklanov on Unsplash
In many python applications, we need to deal with artificial or real-world data. It may not work for us to store all the data in data structures, or we may want to pull or export the data we have from a text file. For this reason, file operations in programming have an essential role. Python also allows users to perform such operations, and it is quite simple to do them. So without further ado let’s start coding!
Basic File Operations
There are many things you can do with files, but in this article, I will only cover the most important parts. These parts are:
- Opening a file
- Reading data from that file
- Writing data into the file
- Closing the file
Opening and Creating a File
If you want to read or create a file, you must open it first using the open method. When you're opening the file, you must specify the file path and which access mode you want to access the file. The syntax should look like this:
open(“file_path”, “access_mode”)
Since we have many different access modes, we need to specify which access mode we want to access the file with when opening the file. Before we see all of the access modes, let’s take a look at the two we will use the most.
- “w” -> Creates the file for writing purposes. If a file already exists, it overwrites the file.
- “a” -> Opens the file in append mode and adds new lines to the end of the file.
When we use the open method, we should not forget to close the file after doing the operations we want to do, like the code snippet below. If we don’t do this, we may run into memory problems.
Therefore, it will be safer for us to use with open, which is another form of file opening, which we will learn shortly.
Writing Files
I mentioned the most basic modes we use when opening files above. Now let’s take a look at other modes.
- w -> Opens a file for writing. If there is an existing file, it will open it and continue by overwriting it. If the file does not exist, it first creates the file in the relevant directory and then starts writing.
- w+ -> Creates a file for reading and writing. The r+ difference deletes and writes the contents of the relevant file.
- a -> In the same logic as w, it does not just delete the relevant content, it adds a new line to the end of the file.
- a+ -> It is used for reading and writing purposes like w+. The w+ difference does not overwrite the content if the file exists. It acts by adding the new data to the end of the file.
- r > It is used for reading files.
- r+ -> It is used for reading and writing purposes. If the file does not exist in the relevant directory, it will throw an error. The new data to be added is appended to the end of the file.
Writing to File
If you want to write the contents of a list (which can be any other data structure) to a text file, you can use a for loop as in the code example below.
OS Module
Also, the OS module in python provides functions for creating and removing a folder. By using the os module you can change and identify the current directory. You can do these operations with the methods in the OS module. But you first need to import the os module to interact with the underlying operating system. For example, you can learn the files in the directory you are working in with the listdir() method or you can check the existence of such a file by using the isfile() method.
With Open
With open is another way to open files. But since we do not need to close the file here, you can use it more easily.
Let’s dig into it with a piece of code. The following piece of code writes the current day-month-year values to the text file.
Reading a File
If we want to read an existing file, we need to use the “r” mode, as the above access modes.
If we try to read a file that does not exist without using with open, as in the example below, we will get a FileNotFoundError.
Therefore, in such a case, we can prevent getting an error by adding the os module and writing an if-else condition. So when the file is not found it will print the file not found.
File Reading Methods
There are various methods for reading files. These are:
- read() -> Used for read all text from a file into a string
- readline() -> Used for line-by-line reading
- readlines() -> Used to read all the lines of the text file and return them as a list of strings.
readline()
readlines()
If we open a file in reading mode and try to write to that file, it will give the error “UnsupportedOperation: not writable”. Like the example below:
Therefore, it is very important to choose an access mode for the purpose we are going to use it. But if you don’t want to get such an error, you can also use the “r+” mode.
Also, if you want to print the file in reverse order, you can use the reversed()method. This method reverses the rows and returns them as a list.
Searching
We can search the file using the file.seek(cursor location) syntax.
- f.seek() -> Moves the cursor as much as the value you give to the seek method.
- f.seek(0,2) > We use to move the cursor to the end of the file
Renaming File
By adding the OS module, we can change the name of our file like the following code. But here, we must be careful that the file exists. Because the method throws an error if it cannot find the file.
We can avoid such an error by using if-else.
Deleting File
If we want to delete a file, we just need to import the os module and use the remove method in the module like the example below.
Today's article was about basic file operations in python, I hope you learned something and liked it. If you liked my post, don’t forget to clap. You can also check out my other articles about Python from here. See you next time!