python: can't work out why len function() is behaving not as expected
Question: i have been working on a python tutorial and have come across a problem which
i simply cannot work out. google has not turned up anything specific and after
a few hours away and much trial and error i still cannot work it out.

anyway, the below code is a simplified version of the tutorial. it works fine
and prints out that my file is 17 bytes long:

    
    
    from sys import argv
    from os.path import exists
    
    script, file1 = argv
    
    file_open = open(file1)
    file_read = file_open.read()
    
    print "the file is %s bytes long" % len(file_read)
    

then the tutorial asks to merge lines 6 and 7 into a single line. if i do it
like this it works:

    
    
    from sys import argv
    from os.path import exists
    
    script, file1 = argv
    
    file_read = open(file1).read()
    
    print "the file is %s bytes long" % len(file_read)
    

but, if i do it like like this then i get an error message which says
`TypeError: object of type 'file' has no len()`:

    
    
    from sys import argv
    from os.path import exists
    
    script, file1 = argv
    
    file_read = open(file1, "r+")
    
    print "the file is %s bytes long" % len(file_read)
    

my problem is i cannot work out why that error message is occurring when i am
adding the "r+" to make sure the open file is read. ( although, is it true
that read is default anyway so maybe even adding the r+ is unnecessary )

any help would be much appreciated. many thanks :)


Answer: I think you forgot the `.read()` in:

    
    
    file_read = open(file1, "r+")
    

so `file_read` is a file object. Try with:

    
    
    file_read = open(file1, "r+").read()
    

and it will return a string as expected.

