How to create new files?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jul 13 10:04:35 CEST 2007


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



More information about the Python-list mailing list