dfsfsdfdsfs
dfsfsdfdsfs

Reputation: 27

Why is max an empty sequence in python

I am a fairly experienced coder, but I am not able to understand this problem within python. The text file that it refers to is laid out as

Jeff 4 7 7
Rich 2 1 9
Chris 4 6 5

Yet when I run the code it works out the first two sets of data but not the last. The code is:

with open(classno, 'r') as f: #it doesn't write last score and 
        for line in f:
            nums_str = line.split()[1:]
            nums = [int(n) for n in nums_str]
            max_in_line = max(nums) #uses last score of it need to combine
            print (max_in_line)
            with open('class11.txt', 'r') as f:
                parts = line.split()
                if len(parts) > 2:
                    name = str(parts[0])
                    f = open(classno, 'a')
                    f.write(("\n") + (name) + (" ") + str(max_in_line))

        f.close()

...but on the final line of the text file it says:

max() arg is an empty sequence

Upvotes: 1

Views: 291

Answers (2)

bav
bav

Reputation: 1623

You redefine f in the most outer with

with open(classno, 'r') as f:

In inner loop:

with open('class11.txt', 'r') as f:

Give different names to these vars.

Upvotes: 3

Adam Hughes
Adam Hughes

Reputation: 16319

Probably you have a newline character at the end of your file, so you're reading in a blank line. Try this:

for line in f:
    if line: 
        ....

Upvotes: 4

Related Questions