Practice Python

Beginner Python exercises

14 December 2014

Read From File Solutions

Exercise 22

Given a .txt file that has a list of a bunch of names, count how many of each name there are in the file, and print out the results to the screen. I have a .txt file for you, if you want to use it!


Sample solution

The basics of reading any file is that you need to read each line one by one, only reading the next line if the next line exists. The skeleton code for this operation is shown here:

  with open('filename.txt') as f:
  	line = f.readline()
  	while line:
  		line = f.readline()

Basically, after you open the file, read one line at a time. Then, check if the line exists using the statement while line, and if it does, get the next line. What happens when the next time line = f.readline() is called and there is no next line? while line the next time around in the loop will return False and the code stops.

Given this skeleton, the first solution counts the different names in the nameslist.txt file.

The line line = line.strip() takes the string read in from the line and gets rid of all whitespaces (including the \n character). And the basic construction and update of the dictionary is very common in many applications.

The second counts how many of each category of image there are in the Training_01.txt file from the SUN image database.

Enjoying Practice Python?

Explore Yubico
Explore Yubico
comments powered by Disqus