2
def file_open(filename):
    fo=open(filename,'r')
    #fo.seek(5)
    fo.read(3)
    fo.close()

file_open("file_ro.py")

I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output!

1
  • i got the answer..need to store it an variable .. Commented Jul 9, 2010 at 8:31

3 Answers 3

7

While your own answer prints the bytes read, it doesn't return them, so you won't be able to use the result somewhere else. Also, there's room for a few other improvements:

  • file_open isn't a good name for the function, since it reads and returns bytes from a file rather than just opening it.
  • You should make sure that you close the file even if fo.read(3) fails. You can use the with statement to solve this issue.

The modified code could look something like this:

def read_first_bytes(filename):
    with open(filename,'r') as f:
        return f.read(3)

Usage:

>>> print read_first_bytes("file.py")
Sign up to request clarification or add additional context in comments.

1 Comment

for python2.5 you can from __future__ import with_statement
1

fo.read() returns the data that was read and you never assign it to anything. You are talking about 'output', but your code isn't supposed to output anything. Are you trying to print those three bytes? In that case you are looking for something like

f = open('file_ro.py', 'r')
print f.read(3)

You are getting the 'expected output' in the interactive prompt, because it prints the result of the evaluation if it is not assigned anywhere (and if it is not None?), just like in the fo.read(3) line. Or something along those lines, - maybe someone can explain it better.

Comments

0
import sys
def file_open(filename):
        fo=open(filename,'r')
        #fo.seek(5)
        read_data=fo.read(3)
        fo.close()
        print read_data
file_open("file.py")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.