Working with text files
Python gives many functions for reading and writing open files.
In this blog, we will be going to explore these functions.
The most familiar file reading and writing functions will be explained in further paragraphs.
Reading text from flies
Python gives mainly three types of reading functions to read from a data file.
But before we read from a file, we need do
the file must be opened and linked through a file object or filehandle in our code.
The most familiar file reading functions of Python are listed below
Method1
read()
Syntax
<filehandle>.read([n])
Explanation
The read method reads at most n bytes;
if n is not specified, it will read the entire file.
Returns the read bytes in the form of a string.
>>> file1 = open("E:\\mydata\\info.txt"> >>> readInfo = file1.read(15) #here we read 15 bytes >>> print (read Info) It's time to re >>> type(readInfo) str #here Bytes read into string type
Method 2
readline()
Syntax
<filehandle>.readline([n])
Explanation
here readline function reads lines of the input, firstly in case n is defined then it will read at most n bytes.
And it Returns the read bytes in the form of a string ending with In(line) character or returns a blank string if no more bytes are left for reading in the file.
>>> file1 = open("E:\\mydata\\info.txt"> >>> readInfo = file1.readline( ) #here we given empty so it will read 1 line >>> print (read Info) It's time to read our files
Method 3
readlines()
Syntax
<filehandle>.readlines()
Explanation
In this method, it reads all lines and returns in a list.
>>> file1 = open("E:\\mydata\\info.txt") >>> readInfo = file1.readline) >>> print(readInfo) ["It's time to work with files. In", 'Files offer and ease and power to store your work/data/information for later use. In', 'simply create a file and store (write) in it .\n', 'Or open an existing file #here we read all lines and read from it.\n'] All lines read >>> type(readInfo) #here we read into list type
These are the syntaxes and explanations for reading a text file in python with the object holding the opened file.
Important point to remember here is:
The open file remains closed by calling the close() method of the file object. Closing the files is important.
In Python, files are by default closed at the end of the code but it is a good habit to get into the mode of closing your files explicitly.
So the pro tip here is: once you finish writing to a file, close it.
Other points to remember
we can combine the file( ) or open() with the file object’s function if we need to perform only a single task to open the file.
You can also combine the open( ) and read( )functions as :
file(“filename”, <mode>).read( )