The file module has functions lock files across several operations that are almost exact equivalents to POSIX API functions; the primary difference is the advantage of valuable return error codes to the application.
For more information about and an example of using file locking, see Atomic File Operations Using File Lock - POSIX.