File Handling in Python - Part 1

A file is like a container where information is stored. Let's take it like this, let's take a bag for an example. The bag is a container where you keep the necessary items you'll be needing, like your gadgets, money, books, and other stuff. A bag keeps those things for you, and anytime you need any of those, you go to the bag, open it, take whatever you need, and then close it. This is exactly how file handling in python operates. Let me walk you through how to handle files in python.

Outline

  • General knowledge of file

  • Types of the file in python

  • Performance process

  • How to create a text file and write content

  • Conclusion

What does file mean?

Files are named locations in disks to store related information. Files store data permanently in non-volatile memory. For example floppy disks. File is a mandatory argument that you have to provide to the open function while rest all arguments are optional and use their default values.

To simply put, the file argument represents the path where your file resides in your system.

Types of file

There are basically two types of files in python. They are:

  1. Text file

  2. Binary file

Text file

Text files contain text or any other file that is related to the text. Text files do not have specific encoding and it can be opened in normal text editors like notepad. Example of text files are listed below

  • Source code: py, js, java, etc.

  • Documents: txt, tet, etc.

  • Web standard: html, json, CSS etc.

  • Configuration: reg, cfg etc.

  • Tabular data: csv, tsv etc.

Binary file

Binary files usually contain images. Most of the files in the computer system are known as binary files. Binary files follow a specific format. They can be opened in the normal text editor but the content present inside the file can't be read, because the binary files will be encoded in the binary format, which can be understood by the computer system only. Examples of binary files are listed below.

  • Image files: .png, .jpg, .gif, etc.

  • Video files: .mp4, .3gp, .avi, etc.

  • Audio files: .mp3, .wav, .mka, etc.

  • Database files: .sqlite, .frm, accde, etc.

  • Document files: .pdf, .doc, .xls, etc.

  • Archive files: .zip, .rar. 7z etc.

  • Executable files: .exe, dll, .class etc.

Performance process

Here, you might want to recall the bag scenario, where I told us about the bag being a container. Remember right? Yes, this is where that bag scenario is totally applicable.

Let's take a look at another scenario of a record book, you open the book, then perform some activities in it. Like you can add, read, edit, and delete names and then close the book. You get it now right?

Now there are four(4) major types of operations that can be handled by python on files. They are:

  • Open

  • Perform tasks(write, read, edit, delete)

  • Close

How to create a text file and write a content

Let's start with the first one which is open, shall we? Python has an in-built function called open() which is used to open a file. It takes a minimum of one argument as seen in the snippet below.

open("file name", "access mode")

The open method returns a file object which is used to access the mode(read, write and other in-built function)

At this point, we will have to pause on this and digress a little bit. Let's talk about Mode. I'm sure when you saw 'the open method returns a file object which is used to access the mode' you'll be like what is mode again?

Okay, a quick one on mode, the mode is the second parameter you have to pass.

Now mode basically states the purpose of opening the file. Like are you opening the file for writing? For reading? For editing?

Write Mode('w'): this mode is used when you want to write data into a file. However, you must remember write mode overwrites the existing data in the file, i.e it will delete the existing file and create a new one if there is none.

fh = open("me.txt", "w")

fh.write("i am incredible, it is written by me.")

fh.close()

Now let's take note when the write comment is executed another file 'me.txt' is created, it's in this file the statement is printed as shown below

fh.write("i am incredible, it is written by me.")

will be displayed. As shown below

i am incredible, it is written by me.

there are three ways file can be written in python. they are: write(string) (for text) write(byte_string) (for binary) writelines(list) The first method was used in the example above.

Read Mode ('r'): this mode opens the file for reading only. It starts reading from the beginning of the file. It is the default mode if any mode is not passed. There are three methods of reading from a file. They are:

read([n]) readline([n]) readlines() For example:


fh = open("me.txt", "r")

print (fh.read())

Here, print function is introduced and it will print the exact statement that was written in the file.

i am incredible, it is written by me.

A for loop statement can be used to read from file also. As shown below

""" this program is to read from file. the file that was created in me.txt  """
fh = open("me.txt", "r") # open the file
for line in fh: # using a for loop
    print(len(line.split(" "))) # checking for the length of words in me.txt

fh.close() # close the file. don't forget to do this

The result is shown in the snippet below.

8

You can see that the result is 8. The interpreter checks the length of words in 'me.txt' and print.

Append Mode ('a'): what this mode does is that it opens a file for appending. Remember that data will be appended at the end of the file pointer. For example:

fh = open("me.txt", "w")

for i in range (1,11):
    fh.write("%d \n" %i) # using formatting function

fh.close()

The result is shown below

1 
2 
3 
4 
5 
6 
7 
8 
9 
10

Note: the file 'me.txt' wasn't deleted but changed after running the command.

Let's take a pause here and have a cup of water. We will continue part 2, where we will be understanding other access modes we have, how you can play around with read and append modes, and so on. I'm sure you are anticipating it. Yes, I am too. See you soon.

Thanks for reading

Free to drop your thoughts