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!
-
i got the answer..need to store it an variable ..webminal.org– webminal.org2010年07月09日 08:31:45 +00:00Commented Jul 9, 2010 at 8:31
3 Answers 3
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_openisn'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")
1 Comment
from __future__ import with_statementfo.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
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")