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.
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)
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.