fname = input("Enter file name: ")
fh = open("mbox-short.txt")
inp = fh.read()
count = 0
for line in fh:
line = line.rstrip()
if not line.startswith("X-DSPAM-Confidence:") :
continue
count = count + 1
c = float(count)
print(len(inp))
average = inp / c
print("Average spam confidence:", average)
The code above should write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
These lines should be counted and the floating point values from each of the lines extracted to compute the average of those values and produce an output as shown below. How could a possible code look like without the usage of the sum() function or a variable named sum in the solution? What is wrong with my code?
You are trying to iterate over an empty object.
The line inp = fh.read()
has exhausted the fh object and it has become set to None
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.