Always Get Better

Posts Tagged ‘python’

Python file upload

Friday, January 2nd, 2009

I recently needed to handle file uploads from a Flash form post using CGI and Python. I made two discoveries:

  1. Python’s CGI library ignores query string variables on POST requests.
  2. After you’ve done it once, working with POST variables whether uploaded files or otherwise is dead simple!

Here is the file I came up with:

import cgi, sys, os

UPLOAD_DIR = “/home/user/uploads”

postVars = cgi.FieldStorage()

if postVars.has_key(“myFile”):
fileitem = postVars[“myFile”]

# If myFile doesn’t contain a FILE, exit
if not fileitem.file:

# Strip file extension
(name,ext) = os.path.splitext( fileitem.filename )

# If a binary file, ensure write flags are binary
if ext == “.jpg” or ext == “.png” or ext == “.gif”:
ioFlag = “wb”
ioFlag = “w”

# Save file data to disk stream
fileObj = file(os.path.join(self.path, fileitem.filename),ioFlag)
while 1:
chunk =
if not chunk: break

Bonus points for checking for and creating a new directory to store the uploaded file in, if needed.

Create Directory in Python

Thursday, January 1st, 2009

I needed to learn how to create directories using Python and found this great resource (digression: check out this author’s page headers – way cool!)

Although I didn’t really add anything new to the code, I ended up creating the following commented function which I share here in case it helps more users to understand.

# If directory (path) doesn’t exist, create it
def createPath(path):
if not os.path.isdir(path):

# Example of Windows file path
createPath( “C:\\Python\\myNewDirectory” )

# Example of Linux file path
createPath( “/home/username/myNewDirectory” )