# File_IO_Demo_Read_File.py # # Anne Lavergne # July 2015 - Modified March 2017 # # Either ask user for a filename (and perhaps also a path) # or # set your filename variables once at the top of your program # Why? inputFile = 'words_7_a.txt' # Demo 1 - Reading a line at a time from a file print("\nDemo 1 - Reading a line at a time from a file.") # Opening a file for reading fileR = open(inputFile, 'r') # Read its first line -> a string firstLine = fileR.readline() print("First line: " , firstLine) print("Data type of variable containing the first line is: ", type(firstLine)) # Read its second line # file object keeps track of where it currently is in the file secondLine = fileR.readline() print("\nSecond line: " , secondLine) # Close the file fileR.close( ) #-------------------------------------- # Demo 2 - Reading a line at a time from a file into a string print("\nDemo 2 - Reading a line at a time from a file.") # Opening a file for reading fileR = open(inputFile, 'r') # Read a line at a time using a for loop for line in fileR: print("\nThe line read from the file is '{}'.".format(line)) print("Data type of variable containing a line is: ", type(line)) strippedLine = line.strip() print("The line once stripped is '{}'.".format(strippedLine)) # Close the file fileR.close( ) #-------------------------------------- # Demo 3 - Reading all lines from a file into a list print("\nDemo 3 - Reading all lines from a file into a list.") # Opening a file for reading fileR = open(inputFile, 'r') # Read all lines from a file into a list myList1 = list(fileR) print("\nFirst list: ", myList1) print("Data type of variable containing all lines form file: ", type(myList1)) # Close the file fileR.close( ) #-------------------------------------- # Demo 4 - Reading all lines from a file into a list print("\nDemo 4 - Reading all lines from a file into a list.") # Opening a file for reading fileR = open(inputFile, 'r') # Read all lines from a file into a list myList2 = fileR.readlines( ) print("\nsecond list: ", myList2) print("Data type of variable containing all lines form file: ", type(myList2)) # Close the file fileR.close( )