# Counts the number of lines in a file (as an example or using fileObject.read()) import sys filename = input( 'Please enter a filename: ' ) mode = 'r' # read mode # Step 1) Open the file # Step 2) Verify successful file open try: infoInputFileObj = open( filename, mode ) # Step 3) Read from or write to the file entireFileContents = infoInputFileObj.read() # reads the entire file as a string except: print('ERROR! Unable to open or read from', filename) sys.exit() # Step 4) Close the file infoInputFileObj.close() # count the number of lines in the (entire) file numberOfNewlines = entireFileContents.count('\n') # check if there's a newline at the very end of the file # if not, count that as an additional line if entireFileContents.endswith( '\n' ) == False: numberOfNewlines += 1 print( filename, 'has', numberOfNewlines, 'lines')