Read file object as string in python

Oli picture Oli · Dec 6, 2008 · Viewed 46.8k times · Source

I'm using urllib2 to read in a page. I need to do a quick regex on the source and pull out a few variables but urllib2 presents as a file object rather than a string.

I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string?

Answer

stesch picture stesch · Dec 6, 2008

You can use Python in interactive mode to search for solutions.

if f is your object, you can enter dir(f) to see all methods and attributes. There's one called read. Enter help(f.read) and it tells you that f.read() is the way to retrieve a string from an file object.