0
def main():
    f = open('yahoo.txt', 'w')
    f.write('yahoo\n')
    f.write('google\n')
    f.write('bing\n')
    f.write('duckduck\n')
    f.write('aol\n')
    f.close()


    f = open('yahoo.txt', 'r')
    print('f.read ', f.read() )
    print('f.read(5)', f.read(5)) # just 'f.read(4)' being printed
main()

in the second last line print('f.read(5)', f.read(5)) just string 'f.read(5)' string is printed and nothing is being printed for the other print argument.

I expect the out to be

 f.read(5) yahoo

Any help is appreciated . thanks

Ramesh-X
  • 4,853
  • 6
  • 46
  • 67

2 Answers2

2

Once you call f.read(), it reads the whole file, moving the cursor to the end of the file. If you want to start reading from the beginning again, you can use the seek function.

def main():
    f = open('yahoo.txt', 'w')
    f.write('yahoo\n')
    f.write('google\n')
    f.write('bing\n')
    f.write('duckduck\n')
    f.write('aol\n')
    f.close()


    f = open('yahoo.txt', 'r')
    print('f.read ', f.read() )
    f.seek(0)   # seek moves the cursor to the beginning of the file
    print('f.read(5)', f.read(5)) # just 'f.read(4)' being printed

main()
Tushar
  • 1,117
  • 1
  • 10
  • 25
1

I suggest you to check documentation. The first one must be reading whole content and moving file offset to the end of file, therefore second read does not read anything because it reaches end of file.

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("")."

You can check seek method to move file position to the beginning of file and read again.

https://docs.python.org/2/tutorial/inputoutput.html

Community
  • 1
  • 1
Validus Oculus
  • 2,756
  • 1
  • 25
  • 34