42. Reading Multiple Lines

  • This example uses a file savedfile.txt with a list of names and reads in each line at a time
  • Each time readline() is called, the file advances by one line
  • This is useful if you know exactly where you saved specific items in the file, and you know how many lines there are in total
  • However, it is no use if you don’t know how many lines are in the file
#Open file for reading
file = open("savedfile.txt","r")

#Read one line after another
line1 = file.readline()
line2 = file.readline()
line3 = file.readline()
line4 = file.readline()

#Close file
file.close()

#Each line when it is read in has a hidden \n at the end that produces
#extra line breaks between each print. Remove it with strip()
line1 = line1.strip("\n")
line2 = line2.strip("\n")
line3 = line3.strip("\n")
line4 = line4.strip("\n")

#Print the lines from the file that have been read in
print(line1)
print(line2)
print(line3)
print(line4)

Tasks

  • Type in the code and make sure it works
  • Modify the program to read the lines into a list and print the contents
  • Save and label your code

Extension Task

One technique to store more than one item per line, is to put a delimiter between them, usually a comma (,) and you can use the split() function to separate the parts of the line when you read it in. Add data into the text file and try to get this technique to work