0

How can i call the 2 functions at the same time or perform a mathematical operation from their results? Every time i call these two functions, only the first function stores the data while the second function shows 0?

fname= input("Enter a file name: ")
try:
    openFile= open(fname, 'r')
except:
    print(fname, "is not found in the directory.")
    quit()

def linecount():
    line_count= 0
    for line in openFile:
        if line.startswith("X-DSPAM-Confidence: "):
            line_count= float(line_count+1)
    return(line_count)


def contents():
    spamContent= 0
    for content in openFile:
        if content.startswith("X-DSPAM-Confidence: "):
            contentconversion= float(content[20:26])
            spamContent= spamContent + contentconversion
    return(spamContent)

result= contents()/linecount()
print(result)
noobie202
  • 11
  • 1
  • 1
    Basic debugging: on each iteration, what is the value of `contentconversion`? If it's `0`, then `spamContent` never gets incremented and the function would return `0`. – Chris Oct 04 '22 at 07:33
  • 1
    You need to open the file at the start of each function. – Dima Chubarov Oct 04 '22 at 07:33
  • 2
    An open file is a stream; once you have read something from it, it is no longer there. The best approach is probably to read the file into memory once, then pass the memory buffer to your functions. This is unrelated to running things "at once". – tripleee Oct 04 '22 at 07:35
  • @tripleee It's still "there", the file pointer is simply at the end, and reading from it yields nothing unless you rewind it. – deceze Oct 04 '22 at 07:36
  • Yes, of course; I'm trying to dumb this down to beginner terminology. – tripleee Oct 04 '22 at 07:36
  • 1
    @tripleee No need to read the file into memory at all, if all the OP does with the data is simple summation as posted in the question. – blhsing Oct 04 '22 at 07:36
  • hey @noobie202, what is the line `contentconversion= float(content[20:26])` in the `contents` function intended to be doing? Is this just a line that contains a number in it? – bn_ln Oct 04 '22 at 07:45
  • @noobie202 Read the file using this code `f = open("file.txt", "r") content = f.readlines()` And provide this content to both functions. – Kiran S Oct 04 '22 at 07:47

0 Answers0