Sunday, October 25, 2020

Python Reading Files

Files are used for reading and writing text and binary data from files. Here will learn how to read, write and manage file resources efficiently. To perform any operation on files the file has to opened first. To open the file we use the built-in python open() function.
open function takes multiple arguments, most commonly used arguments are
file: path to the file to be opened
mode: mode in which the file is to be opened read/write/append and binary/text
encoding: Its better to define the encoding of the file, if no encoding is specified python will choose a  default encoding by sys.getdefaultencoding on that machine.

Now lets see how to read data from file using python programming.

 Character Meaning
 'r' Open for reading (default)
 'w' Open for writing, truncating the file if file exists with same name
 'a' Open for writing, append to the end of file if the file exists
 'b' binary mode
't' text mode (default)

optional modes b,t can be combined with modes r,w,a. so resultant modes might be like 
rb : read binary
wb: write binary
ab : append binary
at  : append text
rt  : read text
wt : write text

Please read the post Python Writing Files before continuing with reading of file.

fp = open('dummyfile.txt',  mode='rt',  encoding='utf-8')

A file pointer fp is created to hold the file object that is opened using the open function, we passed file name, mode of the file and encoding of data in the file. Here the mode of the file is set to read text.

fp.read() 
read function reads the complete file as a single string. 

Resetting the file pointer to the beginning is done using the seek function. fp.seek(0)

To read only specific number of characters from a file using read function, pass the number of characters to be read to the read function. To read first 10 characters from file use fp.read(10)
After this operation file pointer is advanced to the position to the point it has completed reading. To read the remaining file use fp.read()
fp.read() function returns an empty string on file pointer reaching end of file.

Reading file line by line
To read the file line by line use the python readline function. fp.readline()
fp.readline() function returns an empty string on file pointer reaching end of file.

Reading all lines of file into List
To read all lines of file into a single list use python readlines function. fp.readlines() 
readlines function returns a list of all lines within the file.

Close the file
Finally after completion of writing all the required data the file pointer has to be released, this is done by calling close function on the file object.
fp.close()


Download the code from GitHub


No comments:

Post a Comment

Operations on Python Dictionaries