READ A FILE IN PYTHON

Kailash Chandra Behera | Monday, February 01, 2021

Introduction

Here we will see codes to load a file into python or read a text file in python, this article provides codes to read the contents of the file and print all the lines of the file.

Getting Started

The Python read() function is used to read the content of the file which is opened. The contents can be text data, numbers, or binary data. The following code examples read a text file in python. The following codes read a text file in python.

 # Program to show read a text file in python  
 _fileobject=open("D:\aricle.txt",'r')#load file into python  
 str=_fileobject.read();#python read text file  
 print("\nThe contents of aricle.txt are :\n",str)#python printing to file  
 _fileobject.Close() # python close file  

Read File in Python

In the above example file aricle.txt is read using the read() functions. Python read() function returns the read contents and stores them in str, which can be printed later.

File Positions

The python tell() function is used to determine the current position within the file, in other words, the next read will occur at that may byte from the beginning of the file.

 # Program to show read a text file in python  
 _fileobject=open("D:\aricle.txt",'r')#load file into python  
 str=_fileobject.read();#python read text file  
 p=_fileobject.tell(); # python tell function  
 print("\nCurrent position of file :\n",p)#python printing to file  
 _fileobject.Close() #python close function  

tell method in python

Change Positions

The python seek() function to change the current position in a file. This function required two parameters that are offset and the form. The offset parameter indicates the number of bytes to be moved and the form parameter specifies the reference position from where the bytes are to be moved.

 # Program to show read a text file in python  
 _fileobject=open("D:\aricle.txt",'r')#load file into python  
 str=_fileobject.read();#python read text file  
 p=_fileobject.tell(); # python tell function  
 print("\nCurrent position of file :\n",p)#python printing to file  
 _fileobject.seek(0,0)#seek function in python  
 _fileobject.Close() #python close function  

Python File Seek

In the above example form value is 0, which means use the beginning of the file as the reference position. The python seek() function takes three value as form parameter(0,1,2). 1 is for use the current position as the reference position and 2 indicates the position of the file would be taken as the reference position.

Thanks


No comments: