Skip to content

File Handling in Python





Python – File Handling


As we study earlier about Multi threading in Python. Now we will study about a new concept i.e. Python File Handling. In this we will study about some important concepts like Python file i/o, python open mode, python read mode, python write mode, python append mode etc. In Python Programming, File Handling is an important part of Web Application. So lets start.






What is a Stream in File Handling ?



File Handling in Python

Stream is a concept or an interface between Python Code and different devices like Console, Hard Disk, CD-ROM etc. It is used to communicate between devices and python code.


Note : Stream is an object of any stream class.






Types of Stream in Python ?


There are the two types of Stream are :-


  • Byte Oriented Stream : Byte Oriented Stream is a stream that is used to take one byte as input and one byte as output. It is also known as Actual Stream.


  • Character Oriented Stream : Character Oriented Stream is a stream that is used to take one character as input and one character as output. It is also known as Wrapper Stream.

Note : We can Read and Write only two type of data i.e. Byte type or Character type(string type).






Python file modes


There are three different types of python file modes are :-


  • “r” (read mode) : If a file exists then return character stream object associated with given Path or File name and set cursor pointer at the beginning of files. If files do not exist then return error / exception.

  • “w” (write mode) : If a file exists then truncate the file and return associated character oriented stream. If files do not exists then create a new file and returns associated character oriented stream.

  • “a” (append mode) : If a file exists then open a file in write mode and return associated character oriented stream and set cursor pointer at the end of the file. If file not exist then return error. 

Note : The above modes are of Character Oriented Stream.


ModesCharacter Oriented StreamByte Oriented Stream
read mode“r”“rb”
write mode“w”“wb”
append mode “a”“ab”





Python file open





How to Open a File in python ?


We can open a file in python in any modes like read, write and append with the use of built-in open( ) function. 


General syntax to open a file in python :

open("filename", mode)


Python File Example 1 : To open a file in read mode


First of all we should have a text file in the same folder , If a file not exist then create a new text file.

Hello !
Welcome to the Codifyshow !!
The file name is testfile.txt
Thanks

fs = open("testfile", "r")
print(fs.read())

Output 1 :

Hello !

Welcome to the Codifyshow !!

The file name is testfile.txt

Thanks

The open( ) function returns stream object attached with path(filename), which has a read( ) method for reading all the content of the text file.






Example 2 : If the text file is in some other place or is in another folder, we will detect it by its PATH.


fs = open("E:\My Folder\Test_file_2.txt", "r")
print(fs.read())

Output 2 :

Hello !
Welcome to Codifyshow !!
This is the second test_file_2.txt 
Thanks...!!





Python read files





How to read only some parts(characters) of a text file ?


By default, the read( ) method always returns the whole content of the text file, but if you want to read some characters or some parts of the text then you see the example below.


Example : If you want to return first 7 characters of the above text file.

fs = open("testfile", "r")
print(fs.read(7))


Output : First 7 characters including spaces and enters.

Hello !





How to read only lines of the text file ?


we can read only one line of the above text file by using the readline( ) method.


Example 1 : If you want to print only first line.

fs = open("testfile", "r")
print(fs.readline())


Output 1 :

Hello !





Example 2 : If you want to print first two lines.

fs = open("testfile", "r")
print(fs.readline())
print(fs.readline())


Output 2 :

Hello !

Welcome to the Codifyshow !!





Example 3 : If you want to print all the lines at a time of the above text file, then we have to use the readlines() method.

fs = open("testfile", "r")
print(fs.readlines())


Output 3 :

['Hello !\n', 'Welcome to the Codifyshow !!\n', 'The file name is testfile.txt\n', 'Thanks\n', '\n', '\n']





Example 4 : You can also read the whole file with the help of looping.

fs = open("testfile", "r")
for x in fs:
    print(x)


Output 4 :

Hello !

Welcome to the Codifyshow !!

The file name is testfile.txt

Thanks





How to close the files in python ?


You always close the text files when you are finished. It will give you a lot benefit because In some cases it gives you some problems if you do not close it.


Example :

fs=open("testfile", "r")
print(fs.read())
fs.close()


Output :

Hello !
Welcome to the Codifyshow !!
The file name is testfile.txt
Thanks