Python read file line by line example

Reading a text file line by line is pretty easy in python. Basically there are three steps first get a handle on the file using the open() function, then read the file line by line using either readline() or file iterator and finally use the close() method to close it and free up any system resources. But if you are processing say a sound clip or an image file then just add a 'b' to your mode, for example add 'rb' to read a binary file.

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. Basically it creates the resource, performs the code in the block, and then it closes the resource. It's similar to a Try/Catch/Finally block, but without the error handling.

Python read file line by line example
import os
import fileinput

'''
read the whole file
'''
def readAll(filename):
    try:
        with open(filename,'r') as myFile:
            print(myFile.read(), end='')
    except IOError: 
        print("Error: File does not appear to exist.")   
        
    return

'''
read only first 12 characters
'''
def readSome(filename):
    try:
        with open(filename,'r') as myFile:
            print(myFile.read(12), end='')
    except IOError: 
        print("Error: File does not appear to exist.")   
        
    return

'''
read byte by byte  
'''
def readByteByByte(filename):
    try:
        with open(filename,'r') as myFile:
            while True:
                char = myFile.read(1)
                if not char: 
                    break
                print(char, end='')
    except IOError: 
        print("Error: File does not appear to exist.")   
        
    return


'''
read line by line using an iterator
'''
def readLineByLine(filename):
    try:
        with open(filename,'r') as myFile:
            for line in myFile:
                print(line, end='')
    except IOError: 
        print("Error: File does not appear to exist.")   
        
    return

'''
using the fileinput module to read from multiple streams
'''
def readFileInput(filename):
    try:
        with fileinput.input(files=(filename,filename)) as myFile:
            for line in myFile:
                print(line, end='')
    except IOError: 
        print("Error: File does not appear to exist.")   
        
    return

if __name__ == "__main__":
    #path for the current file
    dirPath = os.path.dirname(__file__)
    #path for the filename that we want to read
    filename = os.path.abspath(os.path.join(dirPath, os.pardir,os.pardir,'data/ReadMe.txt'))
    
    readAll(filename)
    readSome(filename)
    readByteByByte(filename)
    readLineByLine(filename)
    readFileInput(filename)


3 comments :

  1. "Things aren't always what they seem," the older cheap fifa 14 coins angel replied. "When we stayed in the basement of the mansion, I noticed there was gold stored in that hole in the wall. Since the owner fifa 14 coins was so bad with greed and unwilling to share his good fortune, I sealed cheap fifa 14 coins the wall so he wouldn’t find it."

    ReplyDelete
  2. Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
    > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK com/itextpdf/text/pdf/fonts/Courier-BoldOblique.afm
    File1: C:\Users\admin\AndroidStudioProjects\pdf3\app\libs\itextpdf-5.5.8.jar
    File2: C:\Users\admin\AndroidStudioProjects\pdf3\app\libs\itextpdf-5.5.8-sources.jar

    ReplyDelete