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!

SilentGhost
322k67 gold badges312 silver badges294 bronze badges
asked Jul 9, 2010 at 8:27
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")
answered Jul 9, 2010 at 8:41
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.

answered Jul 9, 2010 at 8:35

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")
answered Jul 9, 2010 at 8:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.