Day - 42 of DevOps

Day - 42 of DevOps

File handling in in Python

File handling is a cornerstone of programming, and its importance cannot be overstated. It's the process of working with files, which can store various types of data, from text and numbers to images and videos.

Types Of Files Supported By Python

Can you quickly think of all of the types of files that you know? Image, audio, video, text, scripts and many more.

The dependency on the native Operating System is the most important thing to keep in mind when considering the type of files supported.

Windows supports all of the file types mentioned in the first line. But does it support every type of file? Not! There are certain limitations here as well.

Now, coming to Python — There are 2 types of files mainly:

  • Binary

  • Text

Python Files I/O (File Handling In Python) - Trytoprogram

Binary files are categorized as the generic 0’s and 1’s in Python too.

A binary file is any type of file that is not a text file. Because of their nature, binary files can only be processed by an application that knows or understands the file’s structure. In other words, they must be applications that can read and interpret binary.

Text files are structured as a sequence of lines, where each line includes a sequence of characters. This is what you know as code or syntax. Each line is terminated with a special character, called the EOL or End of Line character.

File Operations Using Python — CRUD Operation In Python:

What are the various file operations that you can generally perform?

We call it CRUD. CRUD stands for:

  • Create

  • Read

  • Update

  • Delete

CRUD: Definition, Operations, Benefits How it Works and More

However, do note that many other operations can be performed with the files as well. Such as, copying a file or changing the properties of the file and filter.

All of these operations are important to manipulate the file. This manipulation ensures that the file operations can be performed as per the exact requirement of the user working on the file.

Check the above flow diagram to get a quick picture of what needs to be done. First, we create a file and later open that file. We work on that file — either read or write or anything for that matter. And lastly, we close the file when are doing using it.

Coming to Python now — Creation of file can be done manually or through Python. For now, let us consider that we will do it manually by going to the location and creating a file like a text file.

open() Function in Python:

Now we will check out how we can open a file in Python. It is very simple — we have an inbuilt function called the open function which is used for this exact purpose. The open function takes in 2 parameters — one is the filename and the other is the mode.

And this is the syntax for the open function.

file_object  = open(“filename”, “mode”) where file_object is the variable to add the file object

So what do the 2 parameters mean? One is the filename you want to open. It can be anything at this point of time along with the extension of the filetype. This is important, so make sure to keep this in your mind.

And second, we have the mode. We know this means something to do with opening the file, right? Check this out.

Open Modes:

These are the various modes available to open a file. We can open in read mode, write mode, append mode and create mode as well. Pretty straightforward. But do note that the default mode is the read mode.

Including a mode argument is optional because a default value of ‘r’ will be assumed if it is omitted. The ‘r’ value stands for read mode, which is just one of many.

The modes are:

r’ — Read mode which is used when the file is only being read
w’ — Write mode which is used to edit and write new information to the file (any existing files with the same name will be erased when this mode is activated)
a’ — Appending mode, which is used to add new data to the end of the file; that is new information is automatically amended to the end
r+’ — Special read and write mode, which is used to handle both actions when working with a file

Note that you can open a file in read more only if it exists as well. If you try to read something that doesn’t exist then Python will greet you with a beautiful error message.

In addition, you can specify if the file should be handled as binary or text mode along with the mode as well. You can have the mode as WT so it means that the file is to be opened in the write mode and the file Python is opening is a text file.

Example

f = open(“workfile”,”w”)  
print f

This snippet opens the file named “workfile” in writing mode so that we can make changes to it. The current information stored within the file is also displayed — or printed — for us to view.

Once this has been done, you can move on to call the objects functions. The two most common functions are read and write.

Next in this article, let us look at how we can create a text file using Python.

Creating A Text File Using Python

To get more familiar with text files in Python, what’s better than beginning by creating our own. We will check out some examples as well!

Using any simple text editor of your choice, let’s create a file first. You can name it anything you like at this point, and it’s better to use something you’ll identify with. This is usually done to increase readability. Readability helps to understand the code better, debug and document it as well!

For the purpose of this tutorial, however, we are going to call it “demofile.txt”. Just create the file and leave it blank.

Check out the following code, you could copy the same thing and post it over into your editor as well!

file = open(“demo.txt”,”w”) 
file.write(“Hello World”) 
file.write(“This is our new text file”) 
file.write(“and this is another line.”) 
file.write(“Why? Because we can do it this easily.”) 
file.close()

Output

$ cat demo.txt 
Hello World 
This is our new text file 
and this is another line. 
Why? Because we can do it this easily.

Next in this article, let us look at how we can read a text file using Python.

Reading A Text File In Python

There are so many ways in which you can read a text file in Python. But, let us start with the simple stuff and work on from there.

If you need to extract a string that contains all the characters in the file, you can use the following method:

file.read()

The full code to work with this method will look something like this:

file = open(“demo.txt”, “r”)  
print file.read()

The output of that command will display all the text inside the file, the same text we told the interpreter to add earlier. There’s no need to write it all out again, but if you must know, everything will be shown except for the “$ cat demo.txt” line.

Another way to read a file is to call a certain number of characters.

For example, with the following code, the interpreter will read the first five characters of stored data and return it as a string:

file = open(“demo.txt”, “r”)   
print file.read(5)

Notice how we’re using the same file.read() method, only this time we specify the number of characters to process.

The output for this will look like:

Hello

If you want to read a file line by line — as opposed to pulling the content of the entire file at once — use the readline() function.

Why would you use something like this?

Let’s say you only want to see the first line of the file — or the third. You would execute the readline()function as many times as possible to get the data you were looking for.

Each time you run the method, it will return a string of characters that contains a single line of information from the file.

file = open(“demo.txt”, “r”)  
print file.readline():

This would return the first line of the file, like so:

Hello World

If we wanted to return only the third line in the file, we would use this:

file = open(“testfile.txt”, “r”)  
print file.readline(3):

But what if we wanted to return every line in the file, properly separated? You would use the same function, only in a new form. This is called the file.readlines() function.

file = open(“testfile.txt”, “r”)  
print file.readlines()

The output you would get from this is:

[‘Hello World’, ‘This is our new text file’, ‘and this is another line.’, ‘Why? Because we can.’]

Notice how each line is separated accordingly? Note that this is not the ideal way to show users the content in a file. But it’s great when you want to collect information quickly for personal use during development or recall.