You are currently browsing the daily archive for July 20th, 2008.

Python does not offer a pre-built function that will make a file. Fortunately, it is very simple to create a function that will handle this. Whenever Python is told to read a file, it will look for it wherever you specify it to. However, if that file does not exist, Python will return a IOError exception. That’s when you tell Python to read a file. What happens if you tell Python to write to a file and the file is not there? Python will create that file automatically (not sure if you can turn this off). All you have to do is tell Python to write to a file that does not exist (hence why it is to be created) and Python will create it for you. Here is a function that I’ve tested twice and it worked twice:

def MakeFile(file_name):

	"""
		MakeFile(file_name): makes a file.
	"""

	temp_path = 'C:\\Python25\\' + file_name
	file = open(temp_path, 'w')
	file.write('')
	file.close()
	print 'Execution completed.'

MakeFile('index.html')

And, it can be any file type you want and it can have whatever you want in it. You can even create a blank file. In fact, all files start out blank. Python needs a file to manipulate in order for it to actually manipulate anything. In other words, Python creates a blank file and then writes to it (if there is anything to write). This is why I tested the function twice, by the way.