mimicking a file in memory

Larry Bates larry.bates at websafe.com
Tue Nov 20 16:20:02 EST 2007


p. wrote:
> I am using the mutagen module to extract id3 information from mp3
> files. In order to do this, you give mutagen a filename, which it
> converts into a file object using the python built-in "file" function.
> 
> Unfortunately, my mp3 files don't live locally. They are on a number
> of remote servers which I access using urllib2.
> 
> Here is my dilemma:
> I don't want to copy the files into a local directory for mutagen's
> sake, only to have to remove them afterward. Instead, I'd like to load
> the files into memory and still be able to hand the built-in "file"
> function a filename to access the file in memory.
> 
> Any ideas on how to do this?

Looks like you would need to "hack" the source and replace lines like:

     def load(self, filename):
         self.filename = filename
         fileobj = file(filename, "rb")

with something like:

     def load(self, filename):
         if hasattr(filename, 'read'):
	    fileobj=filename
             if hasattr(filename, 'name'):
                 self.filename = filename
             else:
                 self.filename = 'unknown'

	else:
             self.filename = filename
             fileobj = file(filename, "rb")

-Larry



More information about the Python-list mailing list