O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Opening and Creating Files

The win32file.CreateFile() function opens or creates standard files, returning a handle to the file. Standard files come in many flavors, including synchronous files (where read or write operations don’t return until the operation has completed); asynchronous (or overlapped I/O) files, where read and write operations return immediately; and temporary files that are automatically deleted when the handle is closed. Files may also be opened requesting that Windows not cache any file operations, that no buffering is performed, etc. All the variations that CreateFile() can use are too numerous to list here. For full details, please see the Windows API documentation for CreateFile().

The CreateFile() function takes the following parameters:

  • Name of the file

  • Integer indicating the type of access requested on the file

  • Integer-sharing options for the file

  • Security attributes for the new file or None

  • A flag, indicating what action to take depending on if the file exists

  • A set of flags and attributes for the file itself

  • Another file to act as a template or None

This function returns a PyHANDLE object. PyHANDLEs are simply objects that wrap standard Win32 HANDLEs. When a PyHANDLE object goes out of scope, it’s automatically closed; thus, it’s generally not necessary to close these HANDLEs as it is necessary when using these from C or C++.

Let’s see how these parameters interact and test out some of the documented semantics. Here’s a small script that uses the win32file ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required