Resolving PermissionError: [WinError 32] in Python File Operations

Nov 30, 2025 · Programming · 19 views · 7.8

Keywords: Python | File Operations | PermissionError | Resource Management | Context Manager

Abstract: This article provides an in-depth analysis of the common PermissionError: [WinError 32] in Python programming, which typically occurs when attempting to delete or move files that are being used by other processes. Through a practical image processing script case study, it explains the root cause—improper release of file handles. The article offers standardized solutions using the with statement for automatic resource management and discusses context manager support in the Pillow library. Additional insights cover file locking issues caused by cloud synchronization services and diagnostic methods using tools like Process Explorer, providing developers with comprehensive troubleshooting and resolution strategies.

Problem Background and Error Analysis

During Python file operations, developers frequently encounter the classic PermissionError: [WinError 32] The process cannot access the file because it is being used by another process. This error indicates that the target file is currently locked by a process, preventing deletion, movement, or modification.

In-depth Case Study Analysis

Consider the following image processing script designed to scan a specified directory and delete images with resolution below 1920×1080:

import os
from PIL import Image

while True:    
    img_dir = r"C:\Users\Harold\Google Drive\wallpapers"
    for filename in os.listdir(img_dir):
        filepath = os.path.join(img_dir, filename)
        im = Image.open(filepath)
        x, y = im.size
        totalsize = x*y
        if totalsize < 2073600:
            os.remove(filepath)

When executing this code, a PermissionError is thrown at os.remove(filepath). The fundamental cause is that opening the image file via Image.open() causes the Python process to hold a handle to the file. Attempting to call os.remove() without explicitly closing the file results in the operating system denying the operation because the file remains in use.

Core Solution: Automatic Resource Management

Python's context manager (the with statement) provides an elegant solution for file resource management. The revised code is as follows:

import os
from PIL import Image

while True:    
    img_dir = r"C:\Users\Harold\Google Drive\wallpapers"
    for filename in os.listdir(img_dir):
        filepath = os.path.join(img_dir, filename)
        with Image.open(filepath) as im:
            x, y = im.size
        totalsize = x*y
        if totalsize < 2073600:
            os.remove(filepath)

Using with Image.open(filepath) as im: ensures that the image file is automatically closed upon exiting the context, releasing the file handle. This allows os.remove(filepath) to proceed with the file in an operable state.

Technical Details and Library Selection

It is important to note that development of the original PIL (Python Imaging Library) has largely ceased, and its active fork Pillow is recommended for modern projects. Pillow fully supports the context manager protocol, enabling reliable automatic file closure. If using legacy PIL is necessary due to historical reasons, explicit closure can be employed:

im = Image.open(filepath)
try:
    x, y = im.size
    totalsize = x*y
    if totalsize < 2073600:
        os.remove(filepath)
finally:
    im.close()

Extended Scenarios and Additional Considerations

Beyond code-level file handle management, other factors can cause similar permission errors:

Cloud Synchronization Interference: Services like Google Drive and Dropbox synchronize files in the background, potentially locking files temporarily and causing operation failures. Temporarily pausing synchronization can help identify if this is the contributing factor.

Development Environment Tool Interference: As mentioned in the reference article, VS Code extensions may lock project files. Certain extensions (e.g., file preview, syntax checking tools) access files in the background, leading to file occupancy. Using system tools like Process Explorer can precisely identify which process holds the file lock.

Antivirus Software Impact: Some security software performs real-time scanning of file operations, which may briefly lock files and interfere with normal programming logic.

Best Practices Summary

To avoid permission-related errors in file operations, adhere to the following best practices:

• Prioritize using context managers (with statements) for file operations

• Ensure timely release of resources after file operations

• Consider external factors (cloud synchronization, IDE tools, etc.) in complex environments

• Use modern, actively maintained libraries (e.g., Pillow instead of PIL)

• Utilize system tools for process-level diagnostics when persistent issues arise

Through systematic resource management and consideration of environmental factors, various permission conflicts in Python file operations can be effectively avoided and resolved.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.