mimicking a file in memory

p. ppetrick at gmail.com
Tue Nov 20 16:27:21 EST 2007


On Nov 20, 1:20 pm, Larry Bates <larry.ba... at websafe.com> wrote:
> 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

I thought about this approach originally, but here's the catch there:
the read method isn't the only method i need. mutagen calls the seek
method on the file object. urllib2 returns a "file-like object" that
does not have a seek method associated with it, which means i'd have
to extend urllib2 to add that method. Problem is, i don't know how you
could implement a seek method with urllib2.



More information about the Python-list mailing list