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.

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

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.

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 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.