Handling Files in Python 🐍

December 4th, 2020 5 min read

File handling is one of the most important part of a programmer’s life let him/her be a data scientist, web developer or even a cyber security expert. So I have decided to write this post all about handling files in python.

To open files and bring them in python we have the following syntax,

file = `open(file_name, mode)`

To open a file in read mode we use the following syntax, . The first argument is obviously the file_name and the second one is a bit more interesting in it is the mode in which you want to open the file and it determines whether we can read,append, write , open in binary and so on we will see it down.

For the entirety of this blog post we are going to assume that our python file and our text file which we will be using to perform operations upon are located in the same folder, and the content of the text file is as follows, I have not written it just copied it from a random text generator online as I don’t like lorem ipsum that much.

readme.txt

He found himself holding onto the worst type.
It was the type of secret that could gnaw away at your insides if you didn't tell someone about it, but it could end up getting you killed if you did.

Reading Files

Reading files in python is damn simple, let’s understand it by an example, in this example we will be reading our text file readme.txt` and is located in the same folder as our python files is located.

To open file in read mode we pass 'r' place of mode in the open file syntax, to read the the file don’t worry about these modes I will provide a list at the end of the post with all of the them along with their functions.

main.py

file = open('readme.txt', 'r')

if file.mode == 'r':
    fileContent = file.read()
    print(fileContent)

In above code we are opening a file in read mode and then checking whether it is open in read mode and if it is then we are reading the content of file by using .read() method in it and then printing it.


Creating And Writing Files

Creating and writing files is not so different and can be achieved with only one line of code. Let’s see this all in action.

Here we will use w+ as mode to open the file and when we try to open file with w+ mode it will check if the file exists and if not then it will create the file for us.

sentences =[ "Hello World.", "Every programmer writes it." ]

file = open('notreadme.txt', 'w+')
for sentence in sentences:
    file.write(sentence + '\n')
file.close()

What are we doing above is that we are we first open file in w+ mode then we write each sentence from sentences in file by using write() method on file variable and then at last closing the file after writing it by using file.close() and the file will be written and closed.

In case you have text which contaitns multiple line as one shown below you can use writelines method instead to write multiple lines of text at once .

sentences = "Hello World.\nEvery programmer writes it."

file = open('notreadme.txt', 'w+')
file.writelines(sentences)
file.close()

Appending Files

Appending files means that we edit files what happen when we write data to a file it formats the file and writes new data but if you want to preserve data in a file and new data to it we use a+ as mode.

sentences = "Hello World.\nEvery programmer writes it."

file = open('readme.txt', 'w+')
file.writelines(sentences)
file.close()

We use the same writelines or write method but the only difference is the change in mode from w+ to a+ , and now if we check the readme.txt file then its content would be,

He found himself holding onto the worst type.
It was the type of secret that could gnaw away at your insides if you didn't tell someone about it, but it could end up getting you killed if you did.
Hello World.
Every programmer writes it.

Isn’t that easy.

Guys as I have said here is the table containing all modes with their uses,

Mode Description
β€˜r’ This is the default mode. It Opens file for reading.
β€˜w’ This Mode Opens file for writing. If file does not exist it creates a new file. If file exists it truncates the file.
β€˜x’ Creates a new file. If file already exists the operation fails.
β€˜a’ Open file in append mode. If file does not exist it creates a new file.
β€˜t’ This is the default mode. It opens in text mode.
β€˜b’ This opens in binary mode.
’+’ This will open a file for reading and writing (updating)

Hope you guys like 😊 and if you did then let me know it in the comments, and also read my other posts


You may also like: