Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file object as string in python

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?

like image 986
Oli Avatar asked Dec 06 '08 12:12

Oli


People also ask

How do you convert text to string in Python?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.

What is .read in Python?

Python File read() Method The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.


2 Answers

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.

like image 196
stesch Avatar answered Sep 17 '22 16:09

stesch


From the doc file.read() (my emphasis):

file.read([size])

Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.

Be aware that a regexp search on a large string object may not be efficient, and consider doing the search line-by-line, using file.next() (a file object is its own iterator).

like image 29
gimel Avatar answered Sep 16 '22 16:09

gimel