How to create new files?

Robert Dailey rcdailey at
Thu Jul 12 23:14:37 CEST 2007


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:
	def __init__( self, filename ):
		self.m_file = open( filename, "rwb" )

# 	def __del__( self ):
# 		self.m_file.close()

	def __lshift__( self, data ):
		self.m_file.write( data )

	def __rshift__( self, data ): 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'. I get an exception saying that the file doesn't
exist. I expected it would create the file for me. Is there a way to
make open() create the file if it doesn't exist, or perhaps there's
another function I can use to create the file? I read the python docs,
I wasn't able to find a solution.

Also, you might notice that my "" function is wrong,
according to the python docs at least. read() takes the number of
bytes to read, however I was not able to find a C++ equivalent of
"sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4
byte value from data into python I have no idea how I would do this.

Any help is greatly appreciated. Thanks.

More information about the Python-list mailing list