Data Science Certification Training with Pyth ...
- 86k Enrolled Learners
- Live Class
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:
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 can be used to create server-side applications.
Python can help to do task automation using 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.
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.
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:
“r” = If you want to read from a file.
“w” = If you want to write to a file erasing completely previous data.
“a” = If you want to append to previously written file.
“x” = If you want just to create a file.
Additional used modes to specify the type of file is:
“t” = Text file, Default value.
“b” = binary file. For eg. Images.
fp = open(“my_file.png”, “rb”)
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.
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.
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.
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.
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:
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.