Mastering Python (64 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (28 Blogs)
  • Data Science (39 Blogs)
  • Mastering Python (59 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

Introduction To File Handling In Python

Last updated on May 22,2019 6.8K Views
Research Analyst at Edureka who loves working on Neural Networks and Deep... Research Analyst at Edureka who loves working on Neural Networks and Deep Learning!
29 / 40 Blog from Python Fundamentals

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

File Handling In Python

Python Programming Language is a high-level and interpreted programming language which was created by Guido Van Rossum in 1989. It has been widely used in almost all the domains today and shows no sign of slowing down. This is because of all the features that Python provides to the developers. And, file handling is one among this top feature of Python

According to the website’s survey, Python’s popularity surpassed that of C# in 2018 – just like it surpassed PHP in 2017. On the GitHub platform, Python surpassed Java as the second-most used programming language, with 40% more pull requests opened in 2017 than in 2016.

This makes Python certification one of the most sought-after programming certifications.

In this post on “File Handling in Python” I have included the following topics:

Python File Handling | File Operations in Python | Learn python programming | Edureka

Let’s begin this “File Handling in Python” blog by checking out why we need File Handling!


Why Do You Need File Handling? 

File handling has always been vital to a huge part of the development community. But, why?

Take a minute and think about this situation – You have a server up and running and you need to access files present on that server. You can do this remotely or you need to work with files locally by giving some input to your python program on the server or so.

If I had to answer this personally – I use files a lot for my Deep Learning models to import my data-sets into the program, so I think I agree with a good chunk of the community when I say that usage of files is extremely vital in Python.

So coming back to the basics again – How can we input something to Python?

  • Standard input – The usual keyboard input
  • Command line arguments –  To input some parameter into the code while executing

Python Inputs - File Handling in Python - Edureka

But, think of this situation too – What if you had to read lots and lots of data which is not practical to type in every single time. or even so, it doesn’t make sense to type it out all the time.

So, what is the easiest way out here to store whatever input you want in one place and keep using it as long as your requirement is met? The answer is? Files!

This concept is very easy, I am sure everyone reading this “File Handling in Python” blog will relate to that by the end of the blog.

Working with files basically opens another door among thousands. Each door with Python again opens up to ‘n’ number of opportunities.

Next up in this “File Handling in Python” blog, let us look at the different types of files supported by Python.


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? Absolutely not! There are certain limitations here as well.

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

  • Binary
  • Text

Types of Files - File Handling in Python - EdurekaBinary 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 understand 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.

Next up on this “File Handling in Python” blog, let us look at the different file operations supported by Python.


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 Ops - File Handling in Python - Edureka

However, do note that there are many other operations that 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.

File lifecycle - File Handling in Python - Edureka

Check out 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.

Later on this Python File Handling blog, I will show you how easy it is to make Python create the file for us as well so stay tuned.

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 up on this “File Handling in Python” blog, 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 up on this “File Handling in Python” blog, 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. 

Next up on this “File Handling in Python” blog, let us look at how we can loop over a file object using Python.


Looping Over A File Object In Python

When you want to read – or return – all the lines from a file in a more memory efficient, and fast manner, you can use the loop over method. The advantage to using this method is that the related code is both simple and easy to read. 


file = open(“demo.txt”, “r”) 
for line in file: 
print line

This will return: 

Hello World 
This is our new text file 
and this is another line. 
Why? Because we can. 

See how much simpler that is than the previous methods? 

Next up on this “File Handling in Python” blog, let us look at how we can write a text file using Python.


File Write Method In Python

One thing you’ll notice about the file write method is that it only requires a single parameter, which is the string you want to be written.

This method is used to add information or content to an existing file. To start a new line after you write data to the file, you can add an EOL character.


file = open(“demo.txt”, “w”)

file.write(“This is a test”) 
file.write(“To add more lines.”)

file.close()

Obviously, this will amend our current file to include the two new lines of text. There’s no need to show output. 

Next up on this “File Handling in Python” blog, let us look at how we can close a text file using Python.


Closing A File In Python

When you’re done working, you can use the fh.close() command to end things. What this does is close the file completely, terminating resources in use, in turn freeing them up for the system to deploy elsewhere.

It’s important to understand that when you use the fh.close() method, any further attempts to use the file object will fail.

Notice how we have used this in several of our examples to end interaction with a file? This is a good practice. 

Next up on this “File Handling in Python” blog, let us look at how we can split lines in a text file using Python.


Splitting Lines In A Text File

As a final example, let’s explore a unique function that allows you to split the lines taken from a text file. What this is designed to do, is split the string contained in variable data whenever the interpreter encounters a space character.

But just because we are going to use it to split lines after a space character, doesn’t mean that’s the only way. You can actually split your text using any character you wish – such as a colon, for instance.

The code to do this (also using a with statement) is


with open(“hello.text”, “r”) as f:
data = f.readlines()
 
for line in data:
words = line.split()
print words

If you wanted to use a colon instead of a space to split your text, you would simply change line.split() to line.split(“:”).

The output for this will be:

[“hello”, “world”, “how”, “are”, “you”, “today?”]
[“today”, “is”, “Saturday”]

The reason the words are presented in this manner is that they are stored – and returned – as an array. Be sure to remember this when working with the split function. 


Conclusion

The concepts discussed in this tutorial should help you make your own files and add functionality and operability to the same.

This will be very handy when you are trying to create an application by making the process easy and makes it suited for your personal needs. Now, you should also be able to use these file operations to develop applications easily with the help of Python.

After reading this blog on File Handling using Python, I am pretty sure you want to know more about Python. To know more about Python you can refer the following blogs:

  1. Python Tutorial – Python Programming for Beginners
  2. Python for Data Science
  3. Top 10 Reasons why you should learn Python
  4. Python Requests Tutorial

To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.

I hope you have enjoyed this post on File Handling using Python. If you have any questions regarding this tutorial, please let me know in the comments.

Comments
1 Comment

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.