function.file-get-contents

function.file-get-contents

For offline files: ¶
[code=python] ¶
open(filename).read(1000) # ALWAYS specify a max size (in bytes). See http://sebsauvage.net/python/snyppets/#bound_read ¶
[/code] ¶

For online files (e.g webpage): ¶
[code=python] ¶
# Python 2 ¶
import urllib2 ¶
urllib2.urlopen(url).read(1000) ¶

# Python 3 ¶
import urllib.request ¶
urllib.request.urlopen(url).read(1000) ¶
[/code] ¶

#Python 2 function ¶
[code=python] ¶
import urllib2 ¶
def file_get_contents(filename, use_include_path = 0, context = None, offset = -1, maxlen = -1): ¶
if (filename.find('://') > 0): ¶
ret = urllib2.urlopen(filename).read() ¶
if (offset > 0): ¶
ret = ret[offset:] ¶
if (maxlen > 0): ¶
ret = ret[:maxlen] ¶
return ret ¶
else: ¶
fp = open(filename,'rb') ¶
try: ¶
if (offset > 0): ¶
fp.seek(offset) ¶
ret = fp.read(maxlen) ¶
return ret ¶
finally: ¶
fp.close( ) ¶
[/code]