Counts of integers seen in file aren't being updated

Question:

I made a little script that is supposed to iterate over a text file and read the numbers.
Once a number is read, another variable which measures the frequency of each number is supposed to get updated so that the frequency of the number increases by 1.

I’ve tested every part of this program on its own and they work, however the problems start when I put it all together.

My code is:

import sys

f = open("PythonRandomNums", "r")
ZeroCount = 0
...
NineCount = 0

for x in range(text_file_lines):
current_num = f.readline(x)
if current_num == 0:
ZeroCount += 1
...
elif current_num == 9:
NineCount += 1

obs_freq = [ZeroCount, ... NineCount]
print(f"Observed Frequencies: {obs_freq}")

And the output is

Observed Frequencies: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Asked By: Miguel F. Serna

||

Answers:

readline returns a string. Even if this string only contains digits, it is not equal to a number like 0. And the string actually also contains a newline character.

You need to convert the string to an integer. This will raise an exception if the line does not contain just an integer (plus optional surrounding whitespace).

current_num = int(f.readline())

By the way, iterating over range(text_file_lines) to read from a file is strange. Normally you would iterate directly over the file object, which gives a stream of lines:

for line in f:
    current_num = int(line)
    …

Next, rather than use separate variables for each number, why not use a single dictionary?

count = {}
for line in f:
    current_num = int(line)
    count[current_num] = count.get(current_num, 0) + 1
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.