Sunday, October 30, 2022

[FIXED] Why is len(file.read()) giving me a value of zero?

Issue

Why are the values of print len() different for both functions? Are they not the same?

The file this script is opening was a text file with three lines of text. i named it test.txt and inside it was

Jack and Jill
gave up 
they went home with no water

Code:

def function2nd (filename):
        target = open(theFile, 'r')
        inData = target.read()
        print inData
        print len(inData)
        target.close()
theFile = raw_input("What is the file name?\n>>")
function2nd(theFile)

def function3rd (filename):
        target = open(theFile, 'r')
        target.read()
        print target.read()
        print len(target.read())
        target.close()

function3rd(theFile)

Solution

Files act like a long tape in a casette; you can read the file but by the time you are done you have passed the tape all the way to the end. Reading again won't give you the data again.

As such your second function tried to read data from a file that is already wound all the way to the end.

You can rewind the 'tape' by re-opening the file, or by using target.seek(0) to send it back to the start.



Answered By - Martijn Pieters
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.