Skip to main content

File Handling in Python

 Python File handling a method to store the output of the program to a file or take input from the file. File handling is a key concept in the programming world. File handling used in almost every kind of project. For example, you are creating an Inventory management system.

 Using Python file handling you can store that data into the file. If you are trying to perform some analysis on the data then you must be provided with data in the form comma separated file or Microsoft Excel file. Using file handling you can read data from that file and also store output back into that file.



Two Types of Files:

Python file handling operations also known as Python I/O deal with two types of files. They are:

  • Text files
  • Binary files

Even though the two file types may look the same on the surface, they encode data differently.

A text file is structured as a sequence of lines. And, each line of the text file consists of a sequence of characters. Termination of each line in a text file is denoted with the end of line (EOL). There are a few special characters that are used as EOL, but comma {,} and newlines are the most common ones.

Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf, etc., all of them constitute binary files.




Opening a File

To open a file, the built-in Python Function open() is used. It returns an object of the file which is used along with other functions.

Syntax of the Python open function:

obj=open(file_name , access_mode, buffer)

Here,

  • The file_name refers to the file which we want to open.
  • The access_mode specifies the mode in which the file has to be opened. It can be ‘r’, which is used for opening a file only to read it in Python, or ‘w’ used for opening a file only to write into it. Similarly, ‘a’ opens a file in Python in order to append, and so on. For more access modes, refer to the table given below.
  • The buffer represents whether buffering is performed or not. If the buffer value is 0, then no buffering is performed, and when the buffer value is 1, then line buffering is performed while accessing the file.

Some of the most common access modes are listed below:

ModesDescription
rOpens a file only for reading
rbOpens a file only for reading but in a binary format
wOpens a file only for writing; overwrites the file if the file exists
wbOpens a file only for writing but in a binary format
aOpens a file for appending. It does not overwrite the file, just adds the data in the file, and if file is not created, then it creates a new file
abOpens a file for appending in a binary format

Here’s an example of Python open function and Python readlines for reading files line by line. Say, this is how our text file, ‘demofile.txt’ looks like:

This is just a text file
But this is a newline

Now here’s a code snippet to open the file using file handing in Python.

f= open(‘demofile.txt’, ‘r’)
f.readline()

With the help of the open function of Python read text file, save it in a file object and read lines with the help of the readlines function. Remember that f.readline() reads a single line from the file object. Also, this function leaves a newline character (\n) at the end of the string.

Output:

‘This is just a text file,\n’

Go for this in-depth job-oriented Python Training in Hyderabad now!

Writing into a File

The write() method is used to write a string into a file.

Syntax of the Python write function:

File_object.write(“string”)

Example:

i=open(“demotext.txt”,”w”)
i.write(“Hello Intellipaat”)

Here, we are opening the demotext.txt file into a file object called ‘i’. Now, we can use the write function in order to write something into the file.

Reading from a File

The read() method is used to read data from a file.

Syntax of the Python read function:

File_object.read(data)

Example:

j=open(“intellipaat.txt”,”r”)
k=j.read()
print(k)

Output:

Hello Intellipaat

Closing a File

The close() function is used to close a file.

Syntax of the Python close function:

File_object.close()

Example:

j=open(“intellipaat.txt”,”r”)
k=j.read()
print(k)
j.close()

Output:

Hello Intellipaat

We have the perfect professional Python Course in Bangalore for you!

Methods of File Handling in Python

There are different file handling in Python which are as follows:

  1. rename(): This is used to rename a file.
import os
os.rename(existing file_name, new file_name)
  1. remove(): This method is used to delete a file in Python.
import os
os.remove(“abc.txt”)
  1. chdir(): This method is used to change the current directory.
import os
os.chdir(“new directory path”)
  1. mkdir(): This method is used to create a new directory.
import os
os.mkdir(“new directory path “)
  1. rmdir(): This method is used to remove a directory.
import os
os.rmdir(“new directory path”)
  1. getcwd(): This method is used to show the current working directory.
import os
print(os.getcwd())


Other Methods of File Handling in Python

Following are the other common methods of file handling in Python, along with their descriptions

MethodDescription
close()To close an open file. It has no effect if the file is already closed
flush()To flush the write buffer of the file stream
read(n)To read at most n characters from a file. Remember that it reads till end of file if it is negative or none
readline(n=-1)To read and return one line from a file. Remember that it reads at most n bytes, if specified
readlines(n=-1)To read and return a list of lines from a file. Remember that it reads at most n bytes/characters if specified
seek(offset,from=SEEK_SET)It changes the file position to offset bytes, in reference to  (start, current, or end)
tell()It returns the current file location
writable()It returns true if the file stream can be written to
write(s)To write string s into a file and return the number of characters written
writelines(lines)To write a list of lines into a file

Comments

Popular posts from this blog

Is-A and Has-A relationships in python

  In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. #Is-A relationship --> By Inheritance class  A:    def   __init__ ( self ):      self .b= 10    def   mym1 ( self ):      print ( 'Parent method' ) class  B(A):    def   mym2 ( self ):      print ( 'Child method' ) d = B() d.mym1() #output: Parent method d.mym2() #output: Child method HAS-A Relationship:  Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom. Let’s understand...

Magic Methods in Python

  What Are Dunder Methods ? In Python, special methods are a set of predefined methods you can use to enrich your classes.  They are easy to recognize because they start and end with double underscores, for example  __init__  or  __str__ . Dunder methods let you emulate the behavior of built-in types.  For example, to get the length of a string you can call  len('string') . But an empty class definition doesn’t support this behavior out of the box: These “dunders” or “special methods” in Python are also sometimes called “magic methods.” class NoLenSupport : pass >>> obj = NoLenSupport () >>> len ( obj ) TypeError : "object of type 'NoLenSupport' has no len()" To fix this, you can add a  __len__  dunder method to your class: class LenSupport : def __len__ ( self ): return 42 >>> obj = LenSupport () >>> len ( obj ) 42 Object Initialization:  __init__ "__init __ ...

Inheritance and Types in Python

  Inheritance   Creating a new class from existing class is known as inheritance . The class from which features are inherited is known as base class and the class into which features are derived into is called derived class . Syntax: class  derived- class (base  class ):       < class -suite>      Inheritance promotes reusability of code by reusing already existing classes.  Inheritance is used to implement  is-a  relationship between classes.   Following hierarchy is an example representing inheritance between classes:   Single inheritance   When a derived class inherits only from syntax, the base class is called single inheritance. If it has one base class and one derived class it is called single inheritance.   Diagram     Syntax class  A:  #parent class         #some code       class  b(A):...