Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (86 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

All you Need to Know About File Handling in Python

Last updated on Aug 23,2024 13.1K Views


Python – the undisputed most demanding programming language of 2018 as of StackOverflow survey results. Of all reasons including Data Science, Machine Learning, short-hand syntax styling and many more, the most remarkable feature is File Handling. All those writing to a file and reading to a file can be easily done via Python. Curious enough how it’s done? Let’s get started with this tutorial about  File Handling in Python in the following order:

 

Introduction to Python

Python is a high level, object-oriented programming language. It was developed in 1991 by Guido Van Rossum. Its syntax is similar to the English Language and that is why it enhances code readability. It uses indentation for defining scopes of loops if-else construct, class, etc. 

Python Logo -File Handling in Python

Python can be used to create server-side applications.

  • Python can help to do task automation using Python scripting.

  • Python is used to create stand-alone applications.

  • Python is used in Big Data, data science, Machine Learning……….

Actually the list can go on and on. This defines the power of Python as a programming language. Hence it becomes very important to learn how to write to a file using python and then read from the same file.

 

Importance of File Handling in Python

This question must have stuck your head, isn’t it? Why so buzz and stress on this simple thing. 

Well for that let’s take an example, suppose you want your python script to fetch data from the internet and then process that data. Now if data is small then this processing can be done every time you run the script but in case of humongous data repetitive processing cannot be performed, hence the processed data needs to be stored. This is where data storage or writing to a file comes in. One thing to note while writing data to a file is that its consistency and integrity should be maintained.

Once you have stored your data on a file now the most important thing is it’s retrieval because in computer it’s stored as bits of 1s and 0s and if it’s retrieval is not done properly then it becomes completely useless and data is said to be corrupted.

Hence writing as well as reading is also important aspect of File Handling in python.

 

How to write to a file using Python?

Let’s take an example to understand the standard steps used during File Handling in Python.

  • Opening a file to write.
  • Appending and writing to a file.
  • Closing a file

 

File Handling: Opening

Consider a book you want to write in. First, you need to open that book so that you can write in it. Isn’t it?

Same goes here, first, you need to open file so that you can write to it. So to open a file in python we use the following syntax 

object = open(file_name, mode)

The open function returns the instance of the file that you opened to work on. It takes 2 primarily arguments, file_name and mode. There are four different modes you can open a file to:

  1. “r”  = If you want to read from a file.

  2. “w” = If you want to write to a file erasing completely previous data.

  3. “a” = If you want to append to previously written file.

  4. “x” = If you want just to create a file.

Additional used modes to specify the type of file is:

  1. “t” = Text file, Default value.

  2. “b” = binary file. For eg. Images.

For example:

fp = open(“my_file.png”, “rb”)

This will open a file named my_file.png in binary format.

 

 

Writing in File in Python

To write to a file first, you must open it in write mode and then you can write to it. However, it is important to note that all previously written data will be overwritten.

For this example let’s make a file name edureka.txt and write in it using python.

fp = open(“edureka.txt”, “wt”)
for _ in range(10):
	fp.write(“Edureka is a platform for developing market based skills”)
fp.close()

 

As you can see, to write to a file I have first opened a file named edureka.txt and saved its instance in variable fp. Now I ran a loop 10 times to write “Edureka is a platform for developing market-based skills” in that file 10 times. Now for good programming practice, you must close all the files that you opened.

One thing to note here is to write texts to a file, you must open it in text mode (“t”). If you are working with binary files use “b” while opening the file.

Output-1

Now let us write to a binary file, first thing to remember while writing to a binary file is that data is to be converted into binary format before writing. Moreover, binary data is not human-readable hence you cannot read it by simply opening a file.

fp = open(“binaryFile”, “wb”)
Data = [1,2,3]
fp.write(bytearray(Data))
fp.close()

Here you can see I have first opened binaryFile to write my data into it. Consider I have an array of information to write to a file(in this case Data) then first i converted into binary data by using function bytearray() so that data is converted into binary format. Then, at last, I closed the file.

 

 

Appending to a File

Now, most of the times you will be writing to a file without destroying the earlier contents. To write to a file while preserving previous content is called appending to a file.

For this example let’s append to the same file that we already created. Let’s append to edureka.txt

fp = open(“edureka,txt”, “at”)
for _ in range(5):
	fp.write(“I am appending something to it!”)
fp.close()

Now in the above example, you can see that I have opened a file named edureka.txt using append mode. This tells python that do not overwrite data but start writing from the last line. So what it would do now is that after the ending lines it will add “I am appending something to it!” 5 times. And then we have closed that file.

Output-2-file Handling in Python

 

Closing a File

Well, I have already shown how to close a file. Just use file_reference.close() in python to close an opened file.

For example:

fp = open(“edureka,txt”, “at”)
# Do some work!
fp.close()

 

Now, why is that I have been stressing so much on closing a file?

So there are many reasons:

  • If a file is opened to perform any operations then it’s locked to be opened by any other resource until the process itself closes it.
  • Operating System keeps a check on the number of files opened by a program and thus closing files after use allows you stay within that restriction.
  • Effective Resource management.
  • Good programming practice.

With this, we come to an end of this File Handling in Python article. I hope you got an understanding of Opening, Reading/ Writing and Finally Closing a File in Python.

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.

Got a question for us? Mention them in the comments section of “File Handling in Python” and we will get back to you.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 30th November,2024

30th November

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

All you Need to Know About File Handling in Python

edureka.co