webminal.org
webminal.org

Reputation: 47196

python file read

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!

Upvotes: 2

Views: 5339

Answers (3)

Pär Wieslander
Pär Wieslander

Reputation: 28934

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")

Upvotes: 7

shylent
shylent

Reputation: 10086

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.

Upvotes: 1

webminal.org
webminal.org

Reputation: 47196

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")

Upvotes: 0

Related Questions