October 2, 2023

Python Program to Read a File

In this tutorial we’ll see different options to read a file in Python.

  1. Using read() method you can read the whole file.
  2. Using readline() and readlines() methods you can read file line by line.
  3. More efficient way to read file line by line is to iterate over the file object.
  4. Reading file in binary mode.

1. Using read() method

f.read(size) method reads and returns size bytes. If size argument is not passed or negative, the entire contents of the file will be read and returned.

def read_file(fname):
  try:
    f = open(fname, 'r')
    s = f.read()
    print(s)
  finally:
    f.close()


read_file('F:\\knpcode\\abc.txt')

Here read_file() function is written to read a file which takes file path as argument. File is opened using open() function in read mode and read using read() method. You should always close the file to free the resources which is done in the finally block.

Another way to open the file is using with keyword which automatically closes the file. Using with open is preferred as it makes code shorter.

def read_file(fname):
  with open(fname, 'r') as f:
    s = f.read(9)
    print(s) 

2. Using readline() method to read a file in Python.

f.readline() reads a single line from the file.

def read_file(fname):
  with open(fname, 'r') as f:
    s = f.readline()
    print('Content- ', s)
3. Using readlines() method.

f.readlines() method reads all the lines of a file in a list.

def read_file(fname):
  with open(fname, 'r') as f:
    s = f.readlines()
    print('Content- ', s)

You can also read all the lines of a file by using list(f) function.

def read_file(fname):
  with open(fname, 'r') as f:
    s = list(f)
    print('Content- ', s)

4. Looping over the file object

read(size) or f.readlines() read all the content of the file making it inefficient if the file is large as the whole file will be loaded into the memory. More memory efficient and fast way to read lines from a file is by looping over the file object.

def read_file(fname):
  with open(fname, 'r') as f:
    for line in f:
      # Empty string (‘’) is the EOF char
      print(line, end='')

Similar logic to read the file line by line in Python can also be written using the readline() method.

def read_file(fname):
  with open(fname, 'r') as f:
    line = f.readline()
    while line != '':
      print(line, end='')
      line = f.readline()

5. Reading a binary file in Python.

If you want to read a binary file you need to open file in ‘rb’ mode. In the following Python program to copy an image an image file is opened in binary mode and then written to another file.

def copy_file():
  try:
    f1 = open('F:/knpcode/Java/Java Collections/collection hierarchy.png', 'rb')
    f2 = open('F:/knpcode/Python/newimage.png', 'wb')
    b = f1.read()
    f2.write(b)
    print('Coying image completed...')
  finally:
    f1.close()
    f2.close()

That's all for the topic Python Program to Read a File. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment