Python

Exploring File read and write in python

In the python learning series, we have completed the basic of python in my last series. If you have not checked all posted articles then I would recommend to you please go through all the articles of python from here. Please check the posted  links Understanding Exception Handling in python,  Python OOPS concept with Class, Object and Constructor,
concept of variablesdata typesconditional control, functional control,  Module, and packages and Data Structure (List, Dictionary, and Set) of python.

Now in this tutorial series, we will try to learn about the  File read and write in python. A file has generally three modes which are write, read and append. In python reading the file data or write data into the file is pretty simple and easy. For example, if you want to write something in a file then you need to first open the file in write mode and after you can write data.

Mode:

r(read), w(write), a(append)
r+, w+, a+ – open for updating. w+ will delete the contents

+ means here we are going to update something in this file.  File class has many operations that we need to note down what are the operations and what is the role of them.

  • File.close(): -> Close the file object.
  • file.flush(): -> Flush the internal buffer
  • file.next(): -> File line iterator. e.g for line in fp:
  • file.read([size]): -> Read bytes from the file. The entire file is read if size is negative or not used
  • File.readLine([size]): -> Read one line or size of bytes, whichever is less.

Let’s see how can we open the file in read and write mode to do some action in the file? Let’s see by an example for better understanding.

file1.txt
a:b
c:d
e.f

myscript.py:

rfp = open('file1.txt')
wfp = open('file2.txt', 'w')

data = rfp.read()
wfp.write(data)

rfp.close()
wfp.close()

In the above example, we have file1.txt with some lines. Now I want to open the file for reading and write mode to do some operation. One thing always remembers, once you do the operation in this file and after complete the operation please try to close the file for release the holding reference.

Now let’s learn the few other operations that mostly used in our daily program, For example, reading the file in line by lines etc.

  • file.readlines([size]): -> Return a list of lines in file till eof.
  • file.seek(offset, whence): -> Seek file to offset from whence Whence: os.SEEK_SET(0), os.SEEK_CUR (1), os.SEEK_END(2)
  • file.write(str): -> Write the str to file
  • file.writelines(sequence): ->  Write sequence of strings to file
myscript.py

//rfp = open('file1.txt')
with open('file1.txt') as rfp:
 print rfp.readlines()

In the above example, as we see that we are opening the file with the open keyword. It means if you already open any file earlier then we can use them “with open” keyword as an option.

Now let’s see some other operations that can be used in file or directory. These operations are also used frequently in developing the project.

Module: os.path

  • os.path.abspath(path): return the absolute path
  • os.path.basename(path): last folder name after “/”
  • os.path.dirname(path): top folder name
  • os.path.exists(path): If refers to an existing path or not
  • os.path.expanduser(path): expand ~ to full path
  • os.path.isfile()/isdir()/islink(): check for file type
  • os.path.join(path1, path2): join 2 paths
  • os.path.relpath(path): return the relative path

I think here no need any expanation of the above methods.

Many other methods like comparing the files and directory. Please check the official document for more detail. Now one more important module which we are using for serialized and deserialized the object. That module name is Pickle. Pickle is an Algorithm for python object serialization and deserialization. Let’s understand the few methods of picker module.

  • pickle.dump(obj, file,[protocol]): write serialized data to file
  • pickle.load(file): un-pickle the data in file to object
  • pickle.dumps(obj): dump as a string
  • Pickle.loads(string):Load a string

You can go through the official documentation to play the examples for the pickle module and library.

Summary:

Now we have a good understanding of the File handling of python. We have seen a few examples and play around it to clear the doubts. If you still having issue or doubts then please add a comment I will try to reply as much possible. In my next python tutorial series, we will learn about the Regular expression with the example.

If you are wondering to learn Android then Please Learn from Android category and Wondering to lean Kotlin then Kotlin Category will help you. If you want to learn all python articles, then learn from the python category.

Please do subscribe your email to get the newsletter on this blog on below and if you like this post then do not forget to share like and comment on the below section.

Happy coding 🙂

0 0 votes
Article Rating
Exploring File read and write in python
Share
Published by
Sunil Gupta

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

2 years ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers.… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

3 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

3 years ago