How to create new files?

Robert Dailey rcdailey at gmail.com
Fri Jul 13 10:56:29 EDT 2007


On Jul 13, 3:04 am, Bruno Desthuilliers <bruno.
42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> Robert Dailey a écrit :
>
> > Hi,
>
> > I'm trying to create a Python equivalent of the C++ "ifstream" class,
> > with slight behavior changes.
>
> > Basically, I want to have a "filestream" object that will allow you to
> > overload the '<<' and '>>' operators to stream out and stream in data,
> > respectively. So far this is what I have:
>
> > class filestream:
>
> class Filestream(object):
>
> >    def __init__( self, filename ):
> >            self.m_file = open( filename, "rwb" )
>
> You don't need this C++ 'm_' prefix here - since the use of self is
> mandatory, it's already quite clear that it's an attribute.
>
>
>
> > #  def __del__( self ):
> > #          self.m_file.close()
>
> >    def __lshift__( self, data ):
> >            self.m_file.write( data )
>
> >    def __rshift__( self, data ):
> >            self.m_file.read( data )
>
> > So far, I've found that unlike with the C++ version of fopen(), the
> > Python 'open()' call does not create the file for you when opened
> > using the mode 'w'.
>
> It does. But you're not using 'w', but 'rw'.
>
> > I get an exception saying that the file doesn't
> > exist.
>
> Which is what happens when trying to open an inexistant file in read mode.
>
> > I expected it would create the file for me. Is there a way to
> > make open() create the file if it doesn't exist
>
> yes : open it in write mode.
>
> def __init__( self, filename ):
>      try:
>          self._file = open( filename, "rwb" )
>      except IOError:
>          # looks like filename doesn't exist
>          f = open(filename, 'w')
>          f.close()
>          self._file = open( filename, "rwb" )
>
> Or you can first test with os.path.exists:
>
> def __init__( self, filename ):
>      if not os.path.exists(filename):
>          # looks like filename doesn't exist
>          f = open(filename, 'w')
>          f.close()
>      self._file = open( filename, "rwb" )
>
> HTH

Thanks for the variable naming tips. Is it normal for Python
programmers to create class members with a _ prefixed?

I also figured out why it wasn't creating the file after I had posted,
I realized I was doing "rw" instead of just "w". Thank you for
verifying. Thanks to everyone else for your replies as well.




More information about the Python-list mailing list