Insert Content of a File into a Variable

Cameron Walsh cameron.walsh at gmail.com
Fri Oct 27 05:52:27 CEST 2006


Wijaya Edward wrote:
> Hi,
>  
> How can we slurp all content of a single file 
> into one variable?
>  
> I tried this:
>  
>>>> myfile_content = open('somefile.txt')
>>>> print myfile_content,
> <open file 'somefile.txt', mode 'r' at 0xb7f532e0>
> 
>  
> But it doesn't print the content of the file.

 >>> help(open)
Help on built-in function open in module __builtin__:

open(...)
     open(name[, mode[, buffering]]) -> file object

     Open a file using the file() type, returns a file object.

 >>> help(file)
Help on class file in module __builtin__:

class file(object)
  |  file(name[, mode[, buffering]]) -> file object

<SNIP>

  |read(...)
  |  read([size]) -> read at most size bytes, returned as a string.
  |
  |  If the size argument is negative or omitted, read until EOF is
  |  reached.
  |  Notice that when in non-blocking mode, less data than what was
  |  requested
  |  may be returned, even if no size parameter was given.

<SNIP>

  |readlines(...)
  |  readlines([size]) -> list of strings, each a line from the file.
  |
  |  Call readline() repeatedly and return a list of the lines so read.
  |  The optional size argument, if given, is an approximate bound on the
  |  total number of bytes in the lines returned.

<SNIP>

Those sound useful...

Or alternatively:

 >>> my_file = open('somefile.txt')
 >>> print myfile_content,
<open file 'somefile.txt', mode 'r' at 0xb7f532e0>
 >>> #Hmmm, that's not what I wanted, what can I do with this?
 >>> dir(my_file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', 
'__getattribute__', '__hash__', '__init__', '__iter__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 
'close', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mode', 
'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 
'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 
'xreadlines']
 >>> #That read attribute looks interesting...
 >>> my_file.read
<built-in method read of file object at 0x011750B0>
 >>> my_file.read()

Ye gads!  I wish I'd chosen a shorter file!  Or used a variable to put 
it in! <SNIP>

 >>> text = my_file.read()
 >>> print text

Ye gads!  I wish I'd chosen a shorter file!  <SNIP>


You might also try:
 >>> lines = my_file.readlines()
 >>> for line in lines:
 >>>     print line

<SNIP lots of lines>

Hope it helps,

Cameron.



More information about the Python-list mailing list