tags:

views:

52

answers:

3
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!

A: 
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")
lakshmipathi
return read_data would be better
Blue Peppers
thanks ...it will add it
lakshmipathi
+1  A: 

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.

shylent
+5  A: 

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")
Pär Wieslander
+1 for pointing out the `with`-statement
Space_C0wb0y
for python2.5 you can `from __future__ import with_statement`
gnibbler