Files In Python

Handing Files In Python

Before proceeding make sure you know what files extension means. In most of the programs, we will use the .txt files extension.

Create A New File In Python

A File is not a new term to you. You know how to create a file. Opening a Notepad or any other text editor and typing some text and saving it creates a new file. But wait over there, we know this. What does this as to be done here? Besides we are playing with Python, so we will create a new File using Python.

With Keyword

There are two ways in which you can open a file in Python. First Using with keyword. Just like if, while, and def we have another keyword that is very important to deal with external files, this keyword is with.

with open(file_path) as file_variable:

First with keyword followed by open function() that consists of the file path as the argument, which is then followed by alias i.e., ‘as’ and at last the file_variable. File variable can be any name, that follows the naming variable rule.

Write A File

file = open(file_path,"w") #w is file mode
message = "Forgive me Sasuke….But this is the end!"
with open("fileA.txt","w") as msg_file:

Whenever you open a file, close the opened file. You can now check your current working directory a new file with the file name fileA.txt will be saved. To check its content you need to read the file.

Read The File

When you have created a new file, what next? Obviously, you should even have an idea of how to read the file. Consider the same filename fileA.txt.

file = open(file_path,"r")
with open("fileA.txt","r") as msg_file:
    #You can neglect “r” here as well.
    content =
Forgive me Sasuke….But this is the end!

Appending File

add_more = open("fileA.txt","a")
add_more.write("This message is from Itachi")
read_now = open("fileA.txt")

Well so far so good, we now have our text appended in the file. When you read the file, you can see the message that is newly added. But let us try playing here for a bit.

Forgive me Sasuke….But this is the end!

This is not what we wanted. We added a new message in the file but unfortunately, it is not displaying. Why is that? It is because the file is not closed and whenever you have appended a file, make sure you close the file.

add_more = open("fileA.txt","a")
add_more.write("This message is from Itachi")

read_now = open("fileA.txt")
Forgive me Sasuke….But this is the end!This message is from ItachiThis message is from Itachi

You see, the message is displayed twice because you appended it twice before closing the file completely. Next, you might have noticed the second parameter that we used in the open function, that second parameter is called File Modes.

File Modes

You have already come across three-mode already “w”,”r” and “a”. There are more and here are their meaning.

Opens the file in read-only mode. Starts reading from the beginning of the file and is the default mode for the open() function.
Opens the file as read-only in binary format and starts reading from the beginning of the file. While binary format can be used for different purposes, it is usually used when dealing with things like images, videos, etc.
Opens a file for reading and writing, placing the pointer at the beginning of the file.
Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn't exist.
Opens a write-only file in binary mode.
Opens a file for writing and reading.
Opens a file for writing and reading in binary mode.
Opens a file for appending new information to it. The pointer is placed at the end of the file. A new file is created if one with the same name doesn't exist.
Opens a file for appending in binary mode.
Opens a file for both appending and reading.
Opens a file for both appending and reading in binary mode.

Difference Between Write And Append

So far we have just created a new file using write and append. They do the same task but are completely different. Now say you have an existing file and want to modify it. Now when you use append here, a new line/message is added to the existing file.

But if you try using the ‘w’ mode method, it will override the existing file and add the new data by completely erasing the previous version.

Let us try this in practice.

Create a new file first, so that we can work on the existing file. Sounds good. Let’s proceed.

message = open("message.txt",'w')
message.write("I am message A \nI am message B")

content = open("message.txt")
I am message A 
I am message B

Now we have a new file created. So when you open this file, it is considered an existing file.

new_message = open("message.txt",'a')
#append new message
new_message.write("\nI am message C")

content = open("message.txt")
I am message A 
I am message B
I am message C

As you can observe, while using “a” mode, when you write a new message it appends or is added newly to the existing file. Yes, this is what we required. We are going well.

rewrite_message = open("message.txt",'w')
rewrite_message.write("I am Inevitable, dattebayo")

content = open("message.txt")

Now, what do we have here? While using “w” mode, when you write a new message it completely ignores the existing file and overrides it, and create a new file. Thus when dealing with existing files, we use “a” file mode to add new content to the file. And use “w” to create a new file.

Why Should You Close() The File?

Say, you are on the way to your college/office. You will be taking your bag with you, will the zip of the bag be open or closed? What kind of question is that? Obviously, it will be closed right. You will only open it when you require something inside it and close as soon as your job is done. I guess I am right. In some way, it is the best practice to close the file once you open it. And you have already seen an example for not closing a file while discussing append.

Binary Files

All Images, Documents are in form of Binary. Have you tried opening an image file using with keyword? Try now

with open('itachi.jpg') as img:
    content =
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

When we try opening an image using the open() function, Python is unable to decode the image. But Python can decode your image if and only if it is opened in Binary mode.

with open('itachi.jpg') as img:
    content =
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01…………… [A Long Binary Value]

When the image file is opened using binary mode and on reading it a long binary value is executed. How did we come to the conclusion that the output is in binary mode?

Notice that when you read the binary file, the output starts with b’, which denotes binary data type. Let us consider an example as:

>>> eg = b"101"
>>> type(eg)
<class 'bytes'>

FileNotFoundError In Python

Alright, the basic knowledge in files is you need to understand file paths. These file paths are actually string but convey the location of the particular file. The file might be inside a specific folder. There are times when you will run into an error called FilesNotFoundError.

What causes FileNotFoundError?

Technically speaking: When you are working on a certain application that consists of many supporting files which is added to the main program you might encounter with File Not Found Error. You will encounter this error only when you run your file from a different folder. Say your program and supporting files are saved in the project folder but you are running the program from the Desktop folder, then obviously you will run into File Not Found Error. In order to overcome this issue let’s use the Exception Handling method to write our programs. Note: We will cover Exception Handling In the Next Article.

OS Module In Python

Since we are dealing with files, we might now start working with the OS module, where OS stands for Operating system. OS module is one of the most important modules to deal with directory and files inside the directory. Directory means Folder. Here is a small sneak-peak to OS module.

First, to get started with the os module, we need to import it.

>>> import os
>>> os.getcwd()

getcwd() method returns a file path of the current working directory. Now if you notice the file path, it belongs to Linux Operating System or Mac. As both Mac and Linux are separated by ‘/’.

Creating And Accessing Directory

Firstly create a new directory/folder. Using os.mkdir() we can create a new directory, where mkdir stands for make directory.

>>> import os
>>> os.mkdir("new_directory")
>>> os.getcwd()
>>> os.chdir("new_directory")
>>> os.getcwd()

chdir method is used to change the directory.

Now let’s create two more directories inside the new_directory. The main reason to create two more directories is to check the list of directories or files inside the new_directory.

>>> os.mkdir("dir1")
>>> os.mkdir("dir2")
>>> os.listdir()
['dir1', 'dir2']

Note. os.listdir() will check all the folders as well as files inside the current working directory and rmdir deletes the directory.

>>> os.rmdir("dir1")
>>> os.listdir()
>>> os.rmdir("dir2")
>>> os.listdir()

Summary For Create And Accessing Directory In OS Module:

os.mkdir(): to make a new directory in CWD. (CWD- current working directory.)
os.chdir(): to change the directory
os.listdir(): to display the list of contents(directory and files) in cwd
os.rmdir(): to delete the existing directory.


While opening the file path, In Mac and Linux the path is separated by forward slash ‘/’ and in Windows by backward slash ‘\’. Executing your code in different OS could become difficult. And in such case you can make us of os.path.join method. os.path.join() returns a string data type.

>>> import os
>>> file_path = os.path.join("gintama","four_devas_arc")
>>> file_path

>>> file_path2 = os.path.join("Pictures","Anime")
>>> file_path2


To check if the path exists in your OS. os.path.exists() returns a Boolean Type.

>>> os.path.exists(file_path)

>>> os.path.exists(file_path2)


You can try 30 Days Python Programming by solving amazing code daily. Anime Vyuh Github Organization has a public repo, which will help you with #30DaysOfPython.

Check Out The Previous Tutorials Part On Learn Python.

If you like our content, support us by Buying a Coffee.